PIC Your Malware!
Ben Heimerdinger (Code White), Sebastian Feldmann (Code White)
BruCON 0x0D · Day 1
Overview
In "PIC Your Malware!", Sebastian Feldmann and Ben Heimerdinger of Code White delve into the intricacies of fileless malware evasion, specifically targeting the memory artifacts left by popular in-memory PE loaders. The talk critically examines established techniques like reflective DLLs and Donut, highlighting their inherent weaknesses that enable detection by modern security products. The core of their presentation revolves around leveraging Position Independent Code (PIC) as a more stealthy alternative, significantly reducing an adversary's memory footprint and enhancing evasion capabilities against blue teams.

Key moments
- 0:00 Introduction: Fileless malware and position independent code
- 6:40 Analyzing memory artifacts left by PE loaders
- 11:00 Solution: Writing malware fully as Position Independent Code
- 17:50 Introducing HandleKatz: A stealthy, PIC-based LSASS dumper
- 20:40 Automating creation and protection of PIC tools
- 34:50 Building evasive tooling with GitLab CI/CD pipelines
- 39:00 Demo: Executing HandleKatz via Cobalt Strike
- 42:00 Q&A: Why do operating systems allow RWX memory?
PIC Your Malware!
Speakers: Ben Heimerdinger, Code White; Sebastian Feldmann, Code White
Conference: BruCON
YouTube: https://www.youtube.com/watch?v=8UCBvvJZw2U
Overview
In "PIC Your Malware!", Sebastian Feldmann and Ben Heimerdinger of Code White delve into the intricacies of fileless malware evasion, specifically targeting the memory artifacts left by popular in-memory PE loaders. The talk critically examines established techniques like reflective DLLs and Donut, highlighting their inherent weaknesses that enable detection by modern security products. The core of their presentation revolves around leveraging Position Independent Code (PIC) as a more stealthy alternative, significantly reducing an adversary's memory footprint and enhancing evasion capabilities against blue teams.
The speakers meticulously detail the technical challenges and solutions involved in crafting C code that compiles directly into PIC, bypassing the need for traditional PE file loading mechanisms. They introduce a robust framework for automating the development, obfuscation, and deployment of PIC-based tools, demonstrating how this approach can be integrated into existing red team operations. A significant contribution of their work is the release of HandleKatz, a novel, stealthy LSASS dumper implemented entirely in PIC, designed to circumvent common detection methods such as Sysmon process access events.
This talk is highly relevant for both offensive security practitioners seeking to refine their evasion techniques and defensive teams aiming to understand advanced adversary methodologies. By exposing the limitations of current in-memory detection strategies and offering practical, code-level insights into building truly fileless capabilities, Feldmann and Heimerdinger underscore the continuous arms race in cybersecurity. Their work emphasizes the importance of understanding low-level memory operations and advocating for a shift in defensive focus from static memory analysis to dynamic behavioral monitoring.
Background
▶ Watch: Introduction: Fileless malware and position independent code (0:00)
The evolution of sophisticated malware has increasingly gravitated towards a "plug-and-play" concept, where a small, core module dynamically loads additional capabilities as needed. This modular approach significantly reduces the impact of detection; if one module is flagged, only a small part of the overall malware project is compromised, allowing for rapid re-implementation without burning the entire effort. Historically, these extensions were often dropped as DLLs onto disk and then loaded. However, this method presents two major drawbacks: disk-based artifacts are easily detected by antivirus solutions and sandboxes, and files left on disk are prone to being forgotten by operators, increasing the risk of discovery.
This led to the widespread adoption of fileless malware techniques, which aim to load and execute code entirely in memory, avoiding disk interaction. While this complicates detection for antivirus products, it doesn't eliminate it. Popular fileless techniques, such as reflective DLLs and tools like Donut or sRDI, which claim to convert PEs to shellcode, fundamentally operate as in-memory PE loaders. A reflective DLL embeds its own PE loader, allowing it to self-load from a memory blob. Tools like Donut wrap a PE file with a position-independent PE loader. Despite their perceived stealth, these methods share a critical weakness: they are still PE loaders.
As PE loaders, they necessitate the allocation of executable memory for the loaded PE sections. The common approach involves using the Windows API call VirtualAlloc. The problem is that memory allocated via VirtualAlloc is typically not backed by a file on disk. This results in suspicious memory pages that are executable but lack a legitimate disk association, raising red flags for security products. Furthermore, because a PE file is being loaded, its header (e.g., the "MZ" magic bytes) must reside in private committed memory at some point. While some tools like Donut attempt to wipe the PE header after loading, a temporal window still exists for detection. The presence of a PE header and subsequent PE structure in private, non-file-backed executable memory is a clear indicator of malicious activity, as legitimate executable code should generally originate from disk-backed files. Another approach, executing .NET binaries in memory, faces constant battles with AMSI (Antimalware Scan Interface), requiring continuous bypass development, which is often deemed too "annoying" for red team operations focused on C-based tooling.
Key Findings
▶ Watch: Solution: Writing malware fully as Position Independent Code (11:00)
The central finding of this talk is that Position Independent Code (PIC) offers a significantly stealthier alternative to traditional in-memory PE loaders by eliminating the memory artifacts associated with PE file loading. Unlike reflective DLLs or Donut, PIC does not require a PE file to run, meaning there are never any PE headers, import tables, or relocation tables to parse or load in memory. This fundamentally changes the memory footprint of an injected payload.
The speakers demonstrate that C code can be specifically written and compiled to produce PIC. This involves adhering to strict conditions: no global or static variables (as these require relocations), and techniques like string stacking to handle string literals. A program structured this way lives entirely within its .text segment, which can then be carved out from the compiled PE file and treated as classic shellcode, requiring no initialization. When injected, this PIC results in "no other private committed memory pages popping up," and crucially, "no PE header in memory, and there has never been a PE header in memory." This dramatically reduces the memory artifact fingerprint, making it much harder for memory scanners to identify.
While PIC significantly reduces memory artifacts, the speakers candidly acknowledge that nothing is fully undetectable. Defenders can still monitor for "abnormal allocation of file backed memory itself," although this is "quite prone to false positives." More importantly, even the stealthiest PIC malware will eventually exhibit "awkward behavior" (e.g., unusual network connections, attempts to dump LSASS). This insight leads to their second key finding: the necessity of combining PIC with behavioral evasion techniques.
To illustrate this, they introduce HandleKatz, a custom LSASS dumper. HandleKatz leverages PIC for its core functionality and incorporates a sophisticated handle duplication technique to avoid Sysmon Event ID 10 (Process Access) on LSASS. Instead of directly opening LSASS, HandleKatz identifies benign "handle holder" processes that already possess an open handle to LSASS. By opening the handle holder with PROCESS_DUP_HANDLE and PROCESS_QUERY_INFORMATION access rights, HandleKatz can "steal" and duplicate the existing LSASS handle. This ensures that Sysmon only logs a process access event for the handle holder, effectively camouflaging the interaction with LSASS. Furthermore, HandleKatz avoids the commonly monitored MiniDumpWriteDump API by utilizing and adapting ReactOS code for the actual dumping process, bringing its own "unmonitored" dumping logic. This combination of PIC and behavioral evasion represents a significant advancement in stealthy offensive tooling.
Technical Deep Dive
▶ Watch: Automating creation and protection of PIC tools (20:40)
The core of the Code White team's approach to evasion lies in the meticulous construction and deployment of Position Independent Code (PIC). Their methodology centers on writing C source code that compiles into a PE file whose entire functional logic resides solely within its .text segment, devoid of relocations or reliance on other segments. This is achieved by avoiding global and static variables and employing techniques like string stacking, where strings are dynamically pushed onto the stack at runtime rather than being stored in data segments. Once compiled, the .text segment of this specially crafted PE file can be extracted and used as raw shellcode, requiring no prior initialization or PE loading process.
To streamline the development of such PIC, they have developed a sophisticated scripting pipeline. A key challenge in PIC is manually resolving external functions (e.g., WinAPI calls) since there's no PE loader to handle imports. Their solution involves a script that takes an MSDN URL as input, parses the function definition, and automatically generates a function pointer and a code pattern. This pattern includes an empty character array for the function name, which is later filled with an obfuscated representation by a pre-build script. This pre-build script, obfuscate.py, also generates a random obfuscation_key for each build, then scans the source code for STR: patterns and obfuscates the subsequent string literals, converting them into character arrays. At runtime, these obfuscated strings are de-obfuscated, and a custom GetProcAddress-like logic resolves the function's address. Resolved function pointers are then grouped into a struct and passed around as a single parameter, effectively solving the "no global data" problem.
Beyond PIC generation, the talk details advanced techniques for shellcode protection and evasion. They emphasize self-decrypting shellcode, where the payload is placed in RWX (Read-Write-Execute) memory. When an in-memory scan is triggered, the decryption process runs, ideally taking long enough for the scan to complete before the malicious payload is fully exposed. Their build process for this involves a C template with decryption functionality but no keys. A pre-build script encrypts the actual payload iteratively, writing the generated keys into the template. The number of iterations can be controlled to dictate the decryption time. This template can also be enriched with situational awareness functions for sandbox evasion and environmental encryption, where keys (e.g., expected username) are embedded, causing the shellcode to crash if the environment doesn't match. Preprocessor definitions are extensively used to conditionally compile different functionalities (e.g., 32-bit vs. 64-bit builds, argument handling). A post-build script then crops the .text section and merges it with the encrypted payload to produce the final self-decrypting shellcode.
For further obfuscation, they introduce an intermediate step at the assembly level. Instead of directly compiling C to PIC, they compile C to assembly, then apply mutations and garbage instructions to the assembly code before compiling it into binary. This can also incorporate conditional jumps for evasion: if the expected user context is met, a zero is added to the payload address, and execution proceeds; otherwise, a username-derived number is added, leading to a crash.
The team also leverages loader PEs as vehicles for their shellcode. While direct linking to a loader PE's .text section is ideal for non-self-modifying code (avoiding initial allocations), self-decrypting shellcode requires RWX memory. Their approach uses a Microsoft Visual Studio solution with multiple build configurations, generating DLLs with varying exported functionality or hijack methods. The shellcode itself is linked as a header file, and resource files are added to make the loader blend into the endpoint.
To manage this complex build pipeline, they utilize GitLab CI/CD. This provides modularity and flexibility, allowing parameterization of builds via YAML files and Python scripts. The pipeline defines stages (e.g., pre-build evasion, post-build evasion) and jobs (individual build steps). A dynamic pipeline-specific build YAML file is generated based on the configuration of the main payload and specified evasion modules (e.g., crypto module for Kevin Smith user context, sandbox evasion technique #1, 100 encryption iterations). This system integrates with their C2 infrastructure, specifically Cobalt Strike, enabling operators to trigger obfuscation and evasion processes directly from the UI, uploading and executing payloads like HandleKatz in memory.
HandleKatz Technicals:
HandleKatz, their released LSASS dumper, exemplifies the combination of PIC and behavioral evasion. Traditional LSASS dumping involves opening the LSASS process directly, triggering Sysmon Event ID 10 (Process Access). HandleKatz circumvents this by identifying "handle holder" processes (e.g., LSASS itself, or other benign processes) that already possess an open handle to LSASS. It then opens this handle holder process with PROCESS_DUP_HANDLE and PROCESS_QUERY_INFORMATION access rights. This allows HandleKatz to duplicate the existing LSASS handle without directly accessing LSASS, thus preventing a Sysmon Event ID 10 on LSASS. The dumping itself avoids the commonly detected MiniDumpWriteDump function from dbghelp.dll. Instead, HandleKatz uses a modified version of ReactOS code. They adapted the ReactOS MiniDumpWriteDump equivalent by replacing internal functions and commenting out lines that would otherwise open new handles to the target process. By combining this adapted ReactOS code with EnumerateLoadedModulesW64 and the cloned LSASS handle, HandleKatz performs the dump using direct system calls, writing an obfuscated dump to disk, all without generating a Sysmon process access event for LSASS.
Demo / Proof of Concept
▶ Watch: Building evasive tooling with GitLab CI/CD pipelines (34:50)
The presentation culminates with a live demonstration of HandleKatz, showcasing its stealthy execution and integration within a red team's operational framework. The demo begins by initiating a custom Cobalt Strike CNA script from the team server's UI. This script takes the tool name (HandleKatz) and its arguments as parameters.
Upon execution, the GitLab CI/CD pipeline is triggered:
- Configuration Parsing: The specified parameters for HandleKatz, including evasion modules (e.g.,
crypto moduleconfigured for userKevin Smith, sandbox evasion technique #1, 100 encryption/decryption iterations), are parsed. - Module Cloning: Necessary evasion modules are cloned into the payload repository.
- Build Process: The actual build of HandleKatz as self-decrypting PIC shellcode, incorporating the specified obfuscation and evasion, commences. This step is shown to take a noticeable amount of time, reflecting the complexity of the automated build.
- Deployment and Execution: Once compiled, the resulting shellcode is uploaded to a compromised agent. A sacrificial process is started on the target endpoint, and the HandleKatz shellcode is injected into its memory and executed.
- Result: The demo successfully shows the command returning output to the Cobalt Strike console, but the primary indicator of success is the creation of an obfuscated LSASS dump file on the target endpoint.
To further validate the evasion claims, a video recording of Sysmon events during the HandleKatz execution is played. This visual evidence clearly illustrates:
- The process creation of the sacrificial process used for injection.
- Multiple Process Access events (Sysmon Event ID 10) targeting the "HandleHolder" process (the process from which HandleKatz duplicated the LSASS handle).
- Crucially, no Process Access events are observed for LSASS itself. This directly confirms that HandleKatz successfully bypassed direct interaction with LSASS, thereby avoiding a major detection signature.
- Finally, the process termination of the sacrificial process is shown.
The speakers highlight that since HandleKatz is implemented as PIC, they are unconcerned about it being uploaded to VirusTotal. Its position-independent nature means it can be readily encoded with various shellcode encoders like Shikata Ga Nai (as shown with a screenshot of a VirusTotal scan), allowing operators to easily generate new, signature-evading variants. The tool's code, along with a sample loader and other PIC examples, is available on their GitHub repository.
Defensive Implications
▶ Watch: Q&A: Why do operating systems allow RWX memory? (42:00)
The "PIC Your Malware!" talk presents significant implications for defensive security, necessitating a shift in monitoring strategies. Traditional memory forensics and endpoint detection and response (EDR) solutions that primarily rely on scanning for PE headers, VirtualAlloc calls resulting in RWX memory, or executable memory pages not backed by a disk file will be less effective against sophisticated PIC-based malware. Since PIC doesn't involve a PE loading process, these common artifacts are simply absent.
Defenders must therefore evolve their focus towards advanced behavioral analysis. While PIC reduces memory artifacts, the malicious actions performed by the code (e.g., dumping LSASS, making unusual network connections, modifying system configurations) will still generate observable events. Monitoring for anomalous process behavior, such as a seemingly benign process attempting to access sensitive resources like LSASS, remains critical. However, as demonstrated by HandleKatz, even behavioral indicators can be masked.
Specifically, the handle duplication technique employed by HandleKatz to access LSASS without triggering a direct Sysmon Event ID 10 on LSASS itself is a key defensive challenge. Blue teams need to expand their monitoring of process access events to include not just direct access to critical processes, but also PROCESS_DUP_HANDLE and PROCESS_QUERY_INFORMATION access masks on potential "handle holder" processes. Anomalous duplication of handles to sensitive targets, even if the target itself isn't directly accessed, should be a strong indicator of suspicious activity.
Furthermore, the use of modified ReactOS code for dumping LSASS highlights the inadequacy of relying solely on signatures for known malicious functions like MiniDumpWriteDump. Defenders must consider that adversaries can bring their own implementation of critical functionalities, either by adapting open-source code or writing custom routines. This necessitates a move towards more generic behavioral detection for dumping activities, such as monitoring for large memory reads from sensitive processes combined with subsequent file writes to disk.
The discussion around RWX memory also poses a dilemma. While RWX pages are often a strong indicator of malicious injection, the talk correctly points out legitimate use cases, such as JIT (Just-In-Time) compilation in environments like .NET. This makes a blanket ban or alert on all RWX memory allocations impractical due to high false positive rates. Instead, defenders might explore more nuanced approaches, such as whitelisting known legitimate processes that use RWX pages and scrutinizing any other process that allocates or modifies memory to RWX. The work of Forrest Orr, as recommended by the speakers, provides valuable insights into this complex area.
Finally, the automated build pipeline demonstrated, integrating with C2 frameworks like Cobalt Strike, underscores the need for defenders to understand the rapid iteration capabilities of modern red teams. Signatures based on static analysis of a single payload variant will quickly become obsolete. Defensive strategies must account for dynamic obfuscation, encryption, and custom payload generation, pushing towards detection based on runtime behavior and execution context rather than static indicators.
Key Takeaways
- Position Independent Code (PIC) significantly reduces memory artifacts compared to traditional in-memory PE loaders (reflective DLLs, Donut), as it eliminates the need for PE headers, relocation tables, and non-file-backed executable memory pages, making detection by conventional memory scanners much harder.
- Sophisticated evasion requires a combination of PIC and behavioral stealth. While PIC addresses memory footprint, adversaries must also employ techniques like handle duplication (e.g., HandleKatz for LSASS) and custom implementations of core functionalities (e.g., adapted ReactOS code for dumping) to bypass behavioral monitoring systems like Sysmon.
- Automated build pipelines are crucial for red team efficiency and evasion. Using systems like GitLab CI/CD with pre- and post-build scripts for obfuscation, encryption, situational awareness, and conditional compilation allows for rapid generation of highly customized, polymorphic payloads that can adapt to target environments and bypass static signatures.
- Defenders must shift focus from static memory analysis to advanced behavioral monitoring. Relying solely on the absence of PE artifacts or
VirtualAllocpatterns is insufficient. Instead, monitoring for anomalous process access patterns (including handle duplication), unusual API call sequences, and generic indicators of sensitive data exfiltration is paramount. - The presence of RWX memory is not always malicious. Legitimate applications, particularly those using JIT compilation (e.g., .NET), utilize RWX pages. This complicates detection strategies, requiring defenders to implement more nuanced whitelisting and behavioral profiling rather than blanket alerting on RWX memory.
- Adversaries can "bring their own" code for critical functions. Relying on signatures for known malicious API calls (like
MiniDumpWriteDump) is insufficient when attackers can integrate modified open-source code or custom routines, further pushing detection towards behavioral analysis.
About the Speaker(s)
Sebastian Feldmann and Ben Heimerdinger are security researchers and red team operators at Code White, a Germany-based security firm with offices in Ulm and Mannheim. Their primary focus within the red team is on evasion techniques and the development of offensive tooling. Their expertise lies in understanding the low-level intricacies of operating systems and memory management to craft highly stealthy and effective attack capabilities. This talk showcases their deep technical knowledge in developing advanced malware concepts and building robust, automated pipelines for their deployment.