Defeating EDRs using Dynamic Invocation in C#
Jean-François Maes (Security Researcher; SANS Instructor · TrustedSec), Alessandro Magnosi (Senior Security Consultant · BSI)
BruCON 0x0D · Day 2
Overview
In this insightful BruCON presentation, "Defeating EDRs using Dynamic Invocation in C#," security researchers Jean-François Maes and Alessandro Magnosi delve into the sophisticated techniques modern adversaries employ to bypass Endpoint Detection and Response (EDR) solutions and next-generation antivirus (NGAV). The talk, building upon Maes' prior Black Hat research and Magnosi's "Inceptor" framework, provides a comprehensive historical overview of evasion, from the early days of Metasploit to the current challenges posed by advanced EDRs.

Key moments
- 0:00 Introduction and collaborative EDR research
- 7:00 Evolution of EDRs and bypass challenges
- 14:30 How EDRs hook and detect API calls
- 18:30 Manual mapping and syscalls for EDR bypass
- 26:30 Bypassing AV, AMSI, and sandboxes
- 42:20 Advanced syscall and OPSEC evasion methods
- 49:30 Inceptor: Automating EDR evasion techniques
- 56:00 Audience Q&A and closing remarks
Defeating EDRs using Dynamic Invocation in C#
Speakers: Jean-François Maes (Security Researcher; SANS Instructor, TrustedSec), Alessandro Magnosi (Senior Security Consultant, BSI)
Conference: BruCON
YouTube: https://www.youtube.com/watch?v=bHObB-I2Wiw
Overview
In this insightful BruCON presentation, "Defeating EDRs using Dynamic Invocation in C#," security researchers Jean-François Maes and Alessandro Magnosi delve into the sophisticated techniques modern adversaries employ to bypass Endpoint Detection and Response (EDR) solutions and next-generation antivirus (NGAV). The talk, building upon Maes' prior Black Hat research and Magnosi's "Inceptor" framework, provides a comprehensive historical overview of evasion, from the early days of Metasploit to the current challenges posed by advanced EDRs.
The core of the discussion centers on dynamic invocation methods in C#, specifically leveraging manual mapping of DLLs and direct syscall invocation to circumvent user-land hooks, which are the primary defense mechanism of many EDR systems. Maes and Magnosi meticulously explain how EDRs operate by injecting their own DLLs and hooking critical Windows API functions, and then detail the innovative offensive strategies to detect and bypass these hooks. The collaboration highlights the continuous cat-and-mouse game between offensive and defensive security, offering invaluable insights for both red and blue teams seeking to understand the evolving threat landscape.
This article summarizes the key concepts, technical details, and defensive implications presented in the talk, emphasizing the practical application of these bypasses, particularly through Magnosi's Inceptor framework. It serves as a detailed technical analysis for security professionals grappling with advanced persistent threats and the limitations of current endpoint security solutions.
Background
▶ Watch: Introduction and collaborative EDR research (0:00)
The landscape of offensive security has drastically evolved from the early 2000s, where generating a simple Metasploit Meterpreter payload, dropping it to disk, and executing it often guaranteed a reverse shell. Tools like Shikata Ga Nai provided sufficient obfuscation against nascent antivirus solutions. However, the introduction of Microsoft’s Antimalware Scan Interface (AMSI) marked a significant shift, creating a new hurdle for script-based attacks, particularly those utilizing PowerShell. While AMSI was a step up, it proved to be not without its flaws, often bypassable with relatively low-effort C# interoperability techniques, as demonstrated in the talk with a simple, minimally obfuscated string.
Today, the challenge for attackers is far greater, with the prevalence of EDRs, alongside other host-based defenses like Attack Surface Reduction (ASR) rules, AppLocker, Exploit Guard, and Edge browser protections. Despite the existence of these advanced technologies, the speakers note that many organizations fail to implement or tune them effectively. Referencing leaked playbooks from groups like Conti, they illustrate that even unsophisticated attack chains can succeed against poorly configured environments, emphasizing that hitting even a small percentage of targets is a win for adversaries due to the low effort involved in large-scale campaigns.
To understand modern EDR evasion, a fundamental grasp of the Win32 API is crucial. The Win32 API provides the interfaces for applications to interact with the Windows operating system. A particularly notorious DLL in this context is ntdll.dll, which acts as the critical bridge between user-land (applications) and kernel-land (the operating system core). Any application or shellcode interacting with the Win32 API, such as calling Kernel32.dll!Sleep or VirtualAllocEx, ultimately translates these higher-level calls into lower-level Nt* or Zw* functions within ntdll.dll that then perform the actual system calls.
This makes ntdll.dll a prime target for EDRs. As the speakers provocatively state, EDRs behave like "malware" themselves. They typically inject their own DLLs into processes of interest, often via a kernel driver monitoring process creation. Once injected, they place user-land hooks on key ntdll.dll API calls. By doing so, an EDR can intercept, inspect, and potentially block any malicious activity that attempts to leverage these functions, such as NtAllocateVirtualMemory (called by VirtualAllocEx), NtWriteVirtualMemory, or NtCreateThreadEx. The API Monitor tool is highlighted as a valuable resource for observing this behavior, showing how a high-level VirtualAllocEx call transparently translates to NtAllocateVirtualMemory in the backend, allowing an EDR to detect it at the lower level.
Key Findings
▶ Watch: How EDRs hook and detect API calls (14:30)
The central premise of this talk is that EDRs primarily rely on user-land hooks within ntdll.dll to monitor and intercept malicious activity. These hooks, while effective against standard API calls, also present a critical vulnerability for evasion. The speakers demonstrated that these hooks can be identified by analyzing the initial assembly instructions of ntdll.dll functions. A legitimate Nt* function begins with specific move instructions followed by a syscall instruction, whereas a hooked function will immediately start with a jmp instruction, redirecting execution to the EDR's injected DLL.
The key findings and contributions to EDR bypass techniques include:
- Identification of EDR Hooks: Adversaries can determine which
ntdll.dllfunctions are hooked by comparing their in-memory assembly code against expected patterns. Tools and community efforts, such as Mr. Unicoder's crowdsourced list, aid in cataloging these hooked functions for various EDR products (e.g., CrowdStrike). - Manual Mapping Bypass: By loading a fresh, unhooked copy of
ntdll.dlldirectly into the process's memory space, attackers can call the clean functions without triggering EDR hooks. This "manual mapping" requires the adversary to handle address resolution independently but effectively circumvents the EDR's monitoring of the originalntdll.dll. A more advanced variant, Manual Overload Mapping, utilizesSecImageProtectionto create a section object that is a clean copy ofntdll.dllas if loaded by the Windows loader. - Direct Syscall Invocation Bypass: Instead of relying on the hooked
ntdll.dllwrapper functions, attackers can directly issue syscalls to the kernel. This method bypasses user-land hooks entirely, as the execution path goes straight from user-mode code to the kernel. - Syscall Number Variability: A significant challenge is that syscall numbers (
SSDTindex) are operating system and build-version dependent. - Dynamic Syscall Resolution: Techniques like SysWhispers v1 (static lookup tables), SysWhispers v2 (dynamic resolution based on
ntdllexport table ordering), and Hell's Gate / Halo's Gate (dynamically finding syscall stubs in memory, with Halo's Gate addressing hooked stubs by traversing neighboring functions and patching) are crucial for robust direct syscall implementation. - AMSI Bypass: A straightforward bypass for AMSI involves patching the
AmsiScanBufferfunction in memory. By overwriting specific bytes, the length of the buffer to be scanned (ediregister) can be set to zero, effectively telling AMSI there's nothing to scan. - ETW Bypass: Event Tracing for Windows (ETW) provides valuable telemetry for defenders. Attackers can bypass ETW by either:
- Disabling event registration: Traversing the
EtwpRegistrationTableand unregistering existing ETW providers by callingEtwEventRegisteron their handles. - Patching
EtwEventWrite: Directly modifying theEtwEventWritefunction inntdll.dllto prevent it from logging events. - Sandbox Evasion: A range of techniques can be used to trick sandboxes, including environmental checks (registry keys, file paths), anti-debug measures (DR registers), resource disruption (demanding excessive memory allocations), overly complex or conditional decoding algorithms that time out the sandbox, and "impossible branching" logic.
- Opsec and Blending In: Basic operational security measures like metadata cloning and code signing (even with invalid certificates, as some EDRs only check for the presence of a signature, not its validity) can help payloads appear more legitimate and evade initial detection.
- Inceptor Framework: Alessandro Magnosi's Inceptor framework is presented as a significant contribution, automating the entire process of generating highly evasive payloads. It's template-based, supports multiple languages (C, C++, C#, PowerShell), incorporates various bypasses (AMSI, ETW, WDLP), obfuscation techniques (Chameleon, ConfuserEx, LLVM), and opsec features like metadata cloning and code signing.
These findings collectively highlight that while EDRs have advanced significantly, a deep understanding of their underlying mechanisms allows for the development of effective, multi-layered bypass strategies.
Technical Deep Dive
▶ Watch: Bypassing AV, AMSI, and sandboxes (26:30)
The technical core of the talk revolves around understanding and exploiting the EDR's reliance on user-land hooks. As explained by Jean-François Maes, EDRs operate by injecting their own DLLs into target processes. This injection is often initiated by a kernel driver that monitors process creation. Once injected, the EDR's DLL modifies the prologue of critical ntdll.dll functions, replacing the legitimate initial instructions with a jmp instruction that redirects execution to the EDR's own code. This allows the EDR to intercept the API call, perform analysis, and then either allow the original call to proceed or block it.
To illustrate this, the speakers showed a WinDbg comparison: a normal NtAllocateVirtualMemory function starts with mov instructions to prepare registers and then a syscall instruction. A hooked version, however, immediately begins with a jmp to an address within the EDR's module. This distinct pattern is the key to identifying hooks. Adversaries can enumerate the exported functions of ntdll.dll and compare their starting bytes against the expected Nt* function prologue. Any function not matching the standard mov ... syscall pattern, particularly one starting with a jmp, is likely hooked. Mr. Unicoder's GitHub repository, which crowdsources lists of hooked functions for various EDRs, serves as a practical example of this detection method.
With this understanding, two primary bypass techniques emerge:
- Manual Mapping of
ntdll.dll: This technique involves an attacker loading a fresh, unhooked copy ofntdll.dlldirectly from disk into the process's virtual address space. Since this new copy is not loaded by the standard Windows loader, the EDR's injected DLLs and their hooks on the originalntdll.dllinstance remain untouched. The challenge for the adversary is that they must then manually resolve the addresses of the desired functions within this newly mappedntdll.dll, as the standardGetProcAddresswould return addresses from the hooked, original DLL. This means parsing the PE headers of the manually mapped DLL to find the export table and calculate function offsets. A more refined version, Manual Overload Mapping, aims to replicate the Windows loader's behavior more closely by opening a new section object withSecImageProtection, creating a memory-backed copy ofntdll.dllthat appears more legitimate.
- Direct Syscall Invocation: This technique completely bypasses
ntdll.dll's user-land wrapper functions by directly executing thesyscallinstruction with the appropriate syscall number (also known as the System Service Descriptor Table or SSDT index). Thesyscallinstruction transitions from user-mode to kernel-mode, executing the kernel routine directly. The primary hurdle here is that syscall numbers are not static; they change across different Windows operating system versions and even builds. To overcome this, several dynamic resolution techniques have been developed:
- SysWhispers v1: This early approach relied on pre-compiled lookup tables containing syscall numbers for known OS versions. This is static and requires updates for new Windows versions.
- SysWhispers v2: This improved method dynamically resolves syscall numbers by observing their ordering within
ntdll.dll's export table. While more robust, it still relies on predictable ordering. - Hell's Gate / Halo's Gate: These techniques dynamically locate the syscall stub in memory. Hell's Gate works by scanning
ntdll.dllfor known syscall stub patterns. However, if a function is hooked, its stub pattern will be altered, causing Hell's Gate to fail. Halo's Gate, developed by Renzo (Sector 7), addresses this by first identifying the hooked function. If the expected stub is not found, it traverses neighboring functions until an unhooked stub is located. From this unhooked neighbor, it can deduce the correct syscall number and reconstruct the original stub, effectively "unhooking" the logic in memory for its own use. This is a highly advanced technique to ensure the correct, unhooked syscall instruction is invoked.
Beyond these core EDR bypasses, the talk also detailed several other crucial evasion techniques:
- AMSI Bypass: AMSI's effectiveness can be neutralized by patching the
AmsiScanBufferfunction. Theediregister typically holds the length of the buffer to be scanned. By overwriting the assembly instructions that load this value, specifically replacing them with instructions that setedito zero (e.g.,xor edi, edi), the AMSI scanner is tricked into believing there's no data to analyze, thus allowing malicious content to pass undetected. - ETW Bypass: Event Tracing for Windows (ETW) is a powerful telemetry source for EDRs. Two methods for bypassing ETW were discussed:
- Disabling Event Registration: This involves identifying the global
EtwpRegistrationTablein memory, traversing it to find all registered ETW providers, and then programmatically callingEtwEventRegisteron each of their handles. This effectively unregisters them, preventing further events from being logged by those providers within the process. - Patching
EtwEventWrite: A more direct approach is to patch theEtwEventWritefunction withinntdll.dll. By overwriting its prologue with aretinstruction or ajmpto an invalid address, any attempt to log an ETW event will fail or be redirected, preventing telemetry from being generated. - Sandbox Evasion: To defeat dynamic analysis in sandbox environments, attackers can employ:
- Environmental Checks: Detecting the presence of specific registry keys, file paths, or user accounts common in virtualized analysis environments.
- Anti-Debug Techniques: Checking for debuggers using the
IsDebuggerPresentAPI or directly inspecting theDR(Debug Register) flags. - Resource Disruption: Requesting an unusually large amount of memory (e.g., 1GB heap allocation) that a typical sandbox VM might not provide, causing the analysis to time out or fail.
- Complex or Conditional Decoding: Using decoding algorithms that are either computationally intensive, designed to time out within typical sandbox analysis durations, or only decode under very specific, hard-to-meet environmental conditions.
- Impossible Branching: Incorporating logic that relies on external factors (e.g., specific URLs, network conditions) that are unlikely to be met in a sandbox, thus preventing the malicious payload from executing its core functionality.
- Operational Security (Opsec) and Blending In: Even with advanced technical bypasses, initial detection can be triggered by poor opsec. The talk emphasized:
- Metadata Cloning: Copying legitimate metadata (company name, version info, copyright) from benign executables to make the malicious payload appear more trustworthy.
- Code Signing: Attaching a digital signature to the payload. Even if the certificate is invalid or stolen, some EDRs might only check for the presence of a signature, granting a degree of trust without full validation. Tools like Carbon Copy or SigThief facilitate this.
These detailed technical explanations underscore the complexity of modern EDR evasion and the need for multi-faceted approaches combining low-level system interaction with clever obfuscation and environmental awareness.
Demo / Proof of Concept
▶ Watch: Advanced syscall and OPSEC evasion methods (42:20)
While the talk didn't feature a live, interactive demo of a specific EDR bypass, it served as a comprehensive conceptual demonstration of Alessandro Magnosi's Inceptor framework. Inceptor is presented as an automated, template-based tool designed to streamline the creation of highly evasive payloads that incorporate the advanced techniques discussed throughout the presentation. It acts as a proof of concept for the feasibility and practicality of combining these bypasses into a deployable solution.
The key aspects of Inceptor as demonstrated by Magnosi are:
- Template-Driven Generation: Unlike traditional packers that use fixed loaders, Inceptor allows users to define and use their own custom loader templates. This is a critical feature, as publicly known loaders are quickly fingerprinted and flagged by security vendors. While Inceptor provides default templates, the flexibility to create unique ones ensures longevity of evasion.
- Automatic Shellcode Creation: Inceptor can take various inputs, including .NET DLLs, native DLLs, or .NET executables, and automatically convert them into shellcode suitable for injection.
- Multi-Language Support: The framework supports generating payloads in C, C++, C#, and PowerShell, catering to different adversary needs and target environments.
- Loader-Dependent/Independent Shellcode Encoding: It offers options for shellcode encoding, distinguishing between loader-dependent (where the loader handles decoding, suitable for
Assembly.Loadin C#) and loader-independent (self-decoding) shellcodes. - Built-in Bypass Modules: Inceptor integrates template-based modules for AMSI, ETW, and WDLP (Windows Defender Application Control) bypasses. This modularity means that if a specific bypass technique becomes detected, users can easily spin in their own updated or alternative bypass mechanisms.
- Advanced Obfuscation:
- PowerShell: Utilizes Chameleon, a PowerShell obfuscator developed by Magnosi.
- C#: Supports well-known freely available obfuscators such as ConfuserEx, with provisions for integrating custom obfuscators.
- Native C/C++: Leverages LLVM obfuscation, an intermediate representation obfuscation technique known for its effectiveness against static analysis.
- Anti-Debug and Environmental Checks: Inceptor allows for the inclusion of various modules for anti-debug (e.g., checking DR registers) and environmental checks (e.g., sandbox detection logic) to make payloads more resilient to analysis.
- Automated Compilation and Packing: The framework automates the entire build process. For native binaries, it compiles each module as a static library (
.lib) and links them to create a standalone executable or DLL. For C# applications, it compiles modules into DLLs and then merges them using tools like ILEmerge. - Opsec and Blending-in: Inceptor automatically incorporates metadata cloning and supports various code signing methods, including stealing signatures (e.g., with Carbon Copy) or offline signing (e.g., with SigThief or LazySign), to make the generated payloads appear more legitimate.
In essence, Inceptor aims to be a comprehensive, "batteries-included" solution that abstracts away the manual, tedious, and often error-prone process of combining multiple evasion techniques. By providing a flexible, template-based approach with automated build processes and integrated bypasses, it allows offensive security practitioners to rapidly generate customized, highly evasive payloads. Magnosi actively encourages community contributions to further enhance the framework's capabilities and resilience.
Defensive Implications
▶ Watch: Audience Q&A and closing remarks (56:00)
The detailed exploration of EDR bypasses in this talk presents critical implications for defensive security teams. The primary takeaway is that current EDR reliance on user-land hooks, while a significant improvement over traditional antivirus, is demonstrably insufficient against sophisticated adversaries. Defenders must evolve their strategies beyond simply detecting hooked API calls.
Here are key defensive implications:
- Enhanced Integrity Monitoring of
ntdll.dll: EDRs should implement robust integrity checks forntdll.dlland other critical system DLLs in memory. This includes not just scanning forjmpinstructions at the beginning of API functions but also monitoring for any unauthorized modifications to the.textsection ofntdll.dll. Such monitoring should ideally be performed from a trusted, kernel-mode context to prevent user-land bypasses. - Detection of Direct Syscalls: EDRs need to develop capabilities to detect direct
syscallinstructions that originate from non-ntdll.dllmemory regions or from unusual code paths. Monitoring the context ofsyscallinstructions—e.g., if they are executed from injected code, memory regions without backing on disk, or from processes not typically expected to perform raw syscalls—can be a strong indicator of malicious activity. Integrity checking thesyscallnumbers themselves or theSSDTcan also be valuable. - Advanced Behavioral Analysis: Manual mapping and direct syscalls are often precursors to memory injection or other post-exploitation activities. EDRs should focus on detecting the behavioral chains associated with these techniques, such as unusual memory allocations, attempts to modify memory protection, creation of remote threads, or execution of shellcode, even if the initial API calls are bypassed. Anomalies in process memory (e.g., multiple copies of
ntdll.dllloaded) should raise alerts. - Robust Sandbox Environments: Sandboxes need to be continuously updated to detect the sophisticated evasion techniques discussed. This includes making sandbox environments harder to fingerprint (e.g., by emulating more realistic user activity, providing ample resources, and obscuring typical VM artifacts). Time-based analysis should be extended, and sandboxes should be capable of handling highly complex or conditional decoding logic.
- Comprehensive Code Signature Validation: Relying solely on the presence of a code signature is a critical weakness. EDRs and other security tools must perform full cryptographic validation of code signing certificates, including checking the certificate chain, revocation status, and ensuring the signature matches the file's integrity.
- ETW Monitoring and Protection: While attackers try to disable ETW, defenders should monitor for attempts to unregister ETW providers or patch
EtwEventWrite. This could be done by kernel-level monitoring ofEtwEventRegistercalls or by memory integrity checks on theEtwEventWritefunction. - Proactive Configuration Management: Many bypasses exploit misconfigurations or a lack of proper implementation of existing security controls. Organizations must rigorously implement and tune controls like Attack Surface Reduction (ASR) rules, AppLocker, and Windows Defender Application Control (WDAC) to block common attack vectors and restrict unauthorized execution.
- Understanding Adversary Tooling: Blue teams should familiarize themselves with tools like Inceptor, SysWhispers, and Hell's Gate/Halo's Gate. Understanding how these tools operate allows defenders to anticipate attack methods and develop specific detection rules. Collaboration with offensive security researchers (e.g., through purple teaming) is crucial for this.
In summary, defending against these advanced techniques requires a shift from signature-based or simple hook-based detection to a multi-layered approach that combines low-level system integrity monitoring, sophisticated behavioral analytics, and robust configuration management, all informed by a deep understanding of offensive methodologies.
Key Takeaways
- EDR user-land hooks are bypassable: Modern EDRs heavily rely on hooking
ntdll.dllfunctions in user-land, but these hooks can be identified and circumvented by sophisticated adversaries. - Manual mapping and direct syscalls are potent evasion techniques: Loading an unhooked copy of
ntdll.dll(manual mapping) or directly invoking kernel functions viasyscallinstructions bypasses EDR user-land monitoring. - Dynamic syscall resolution is crucial: Syscall numbers vary by OS version, necessitating dynamic techniques like SysWhispers v2 or Halo's Gate to reliably invoke syscalls without hardcoding.
- AMSI, ETW, and sandbox can be neutralized: Specific techniques exist to disable AMSI scanning (patching buffer length), prevent ETW telemetry (unregistering providers, patching
EtwEventWrite), and evade sandbox analysis (environmental checks, resource disruption, complex decoding). - Opsec matters for initial evasion: Even simple measures like metadata cloning and code signing (even if invalid) can help payloads appear legitimate and avoid initial scrutiny.
- Automated frameworks streamline advanced evasion: Tools like the Inceptor framework demonstrate how a combination of these advanced bypasses, obfuscation, and opsec can be automated to generate highly evasive, custom payloads.
About the Speaker(s)
Jean-François Maes is a Security Researcher at TrustedSec and a SANS Instructor, teaching the SEC699 Purple Team course. Known for his contributions to the cybersecurity community, he regularly develops and releases tools on GitHub, often referring to them as "barely functioning" but serving as valuable learning experiences and contributions to offensive security research. His work, including prior presentations at Black Hat, forms the foundation for discussions on advanced EDR evasion techniques.
Alessandro Magnosi is a Senior Security Consultant at BSI. He is an active "toolsmith" who develops and releases numerous public tools to aid his daily red teaming work and bug bounty pursuits. Magnosi is a strong advocate for sharing knowledge and tools within the community, believing that collaborative efforts lead to greater improvement. His Inceptor framework, designed to automate complex EDR bypass techniques, exemplifies his commitment to advancing offensive security capabilities.