AMSI Patching: Deconstructing the Art of Disabling Antivirus via Memory Manipulation
A deep dive into AMSI Patching, exploring the advanced memory manipulation techniques adversaries use to hot-patch system DLLs and silently blind Windows Defender during attacks.
In the sophisticated realm of modern cyber warfare, attackers rely heavily on stealth. Executing malicious payloads—whether it be a ransomware encryptor, a Cobalt Strike beacon, or a custom PowerShell keylogger—requires bypassing the operating system's native defenses. For Windows environments, the primary hurdle for script-based and fileless malware is the Antimalware Scan Interface (AMSI). Designed to intercept and scan de-obfuscated script content before execution, AMSI poses a formidable challenge. While early evasion techniques relied on simple string obfuscation or manipulating PowerShell's internal state via Reflection, Microsoft rapidly closed those loopholes. In response, advanced threat actors escalated their tactics to a much lower, highly technical level: AMSI Memory Patching.
AMSI Patching (often referred to as function hooking or memory stomping) is an elegant, surgical attack against the very fabric of the operating system's memory space. Instead of trying to trick the scanner with complex obfuscation, the attacker simply edits the scanner's code in live memory, permanently lobotomizing the specific amsi.dll instance loaded within the compromised process. By overwriting just a few critical bytes of assembly instruction, the adversary ensures that every malicious script presented to AMSI is immediately deemed safe. This comprehensive article deconstructs the mechanics of AMSI Memory Patching, exploring how attackers locate the critical functions, the specific Windows APIs utilized to manipulate memory, and the advanced strategies required to detect and prevent these low-level evasion techniques.
The Mechanics of Memory Patching
To understand AMSI Patching, one must grasp how Windows manages dynamic link libraries (DLLs) and process memory. When a script engine like PowerShell (powershell.exe) starts, it loads several necessary DLLs into its own, isolated virtual memory space. One of these is amsi.dll.
The Target: AmsiScanBuffer
Within the amsi.dll library reside several exported functions, the most critical being AmsiScanBuffer. This is the exact function called by PowerShell to hand over the raw script content to the underlying antivirus engine (like Windows Defender) for analysis.
If an attacker wants to execute a malicious script, they must ensure that AmsiScanBuffer never actually performs the scan. The memory patching technique involves modifying the live, executable code of AmsiScanBuffer while it is sitting in the RAM of the PowerShell process. The attacker's goal is to inject a tiny instruction that causes the function to instantly terminate and return a specific code: AMSI_RESULT_CLEAN. When PowerShell receives this specific return code, it assumes the antivirus has given the green light, and it executes the malicious script without hesitation.
The Execution Flow: Locating and Modifying
Executing an AMSI patch requires precision and the utilization of specific, powerful Windows Application Programming Interfaces (APIs). The attack typically follows a strict, three-step sequence:
- Locate the Function (GetProcAddress): The malicious script (often an initial, heavily obfuscated "stager" script) first needs to find the exact memory address where
AmsiScanBufferis located. It uses theLoadLibraryAPI to get a handle toamsi.dll, and then uses theGetProcAddressAPI, asking the operating system, "At what exact memory address doesAmsiScanBufferstart?" - Change Memory Protections (VirtualProtect): By default, modern operating systems implement strict memory protections. The memory region containing the executable code of
amsi.dllis marked asRX(Read/Execute). If a script attempts to write new data into this region, the OS will instantly terminate the process with an Access Violation error. To bypass this, the attacker must call the highly restrictedVirtualProtectAPI. They request the OS to temporarily change the memory protection of theAmsiScanBufferaddress space fromRXtoRWX(Read/Write/Execute), granting the script the authority to alter the live code. - Overwrite the Code (WriteProcessMemory or Marshal.Copy): With the memory now writable, the attacker executes the patch. They utilize APIs like
WriteProcessMemory(or .NET'sMarshal.Copy) to overwrite the first few bytes of theAmsiScanBufferfunction. They inject a specific hexadecimal byte sequence—representing assembly instructions—that forces the function to immediately return an error code (like0x80070057for E_INVALIDARG) or the clean code.
Once the bytes are overwritten, the attacker optionally restores the memory protections back to RX to maintain stealth. From that exact microsecond forward, any subsequent script executed in that specific PowerShell session will trigger the patched AmsiScanBuffer, instantly returning a "safe" result, rendering AMSI completely blind.
Advanced Patching Variations and Stealth
As security solutions evolved to detect the standard AMSI patching byte sequences, attackers refined their techniques, introducing variations to maintain operational security and evade signature-based detection.
Bypassing API Hooks
Advanced Endpoint Detection and Response (EDR) solutions actively monitor the critical Windows APIs used for patching, such as VirtualProtect and WriteProcessMemory. If an EDR detects a script attempting to call VirtualProtect on the memory region of amsi.dll, it will instantly kill the process.
To circumvent EDR hooks, sophisticated attackers utilize a technique called "Direct System Calls" (Syscalls). Instead of calling the high-level, monitored VirtualProtect API, the attacker's code bypasses the Windows API layer entirely. It manually loads the exact assembly instructions required to transition the CPU into kernel mode and directly requests the kernel to alter the memory protections. Because the EDR is monitoring the high-level API and not the raw system call execution, the memory patch occurs silently beneath the EDR's radar.
Dynamic Patching and Hardware Breakpoints
To further evade detection, attackers utilize dynamic patching techniques. Instead of hardcoding the specific byte sequence to overwrite AmsiScanBuffer (which can be easily flagged by antivirus signatures), the stager script dynamically calculates the necessary bytes at runtime based on the specific architecture (x86 vs x64) and Windows version.
An even more advanced, though less common, technique involves the use of Hardware Breakpoints. Instead of physically overwriting the bytes in memory, an attacker with sufficient privileges can set a hardware breakpoint on the CPU specifically targeting the memory address of AmsiScanBuffer. When the CPU attempts to execute the function, the breakpoint triggers an exception, handing control to a malicious exception handler established by the attacker. This handler spoofs the AMSI_RESULT_CLEAN return value and resumes execution, completely blinding AMSI without modifying a single byte of the amsi.dll code in memory, making it incredibly difficult for traditional integrity checks to detect.
Defensive Strategies and Detection
Detecting and mitigating AMSI memory patching requires a defense-in-depth approach that shifts focus from static script analysis to aggressive behavioral monitoring and structural architectural hardening.
Enforcing Constrained Language Mode (CLM)
The most effective architectural defense against script-based memory patching in PowerShell is the strict enforcement of Constrained Language Mode (CLM) via Windows Defender Application Control (WDAC) or AppLocker.
Executing a memory patch inherently requires the script to interact with low-level Windows APIs (VirtualProtect, Marshal.Copy). When CLM is active, PowerShell operates in a highly restricted sandbox. It is explicitly blocked from utilizing the advanced .NET types, P/Invoke signatures, and COM objects required to interact directly with system memory. If an attacker attempts to execute an AMSI patching stager in a CLM-enforced environment, PowerShell will simply block the API calls, neutralizing the attack entirely and preserving the integrity of AMSI.
Advanced EDR and Behavioral Telemetry
Traditional signature-based antivirus is largely blind to the act of memory patching itself. Organizations must deploy advanced EDR platforms that prioritize behavioral telemetry and memory analysis.
A mature EDR solution does not just scan files; it monitors the actions of processes in real-time. The EDR actively monitors the memory protections of critical system DLLs. If it detects a highly anomalous event—such as a PowerShell process suddenly requesting RWX (Read/Write/Execute) permissions specifically over the memory region occupied by amsi.dll—the EDR immediately recognizes this as a high-confidence indicator of an AMSI patching attempt and terminates the process before the patch can be applied. Furthermore, EDRs routinely perform memory integrity checks, actively scanning the live RAM to ensure the bytes of AmsiScanBuffer match the original, digitally signed version on the disk, instantly detecting if an overwrite has occurred.
Comprehensive Script Block Logging
Because determined adversaries will occasionally succeed in blinding AMSI, organizations must never rely on it as their sole source of visibility. Defenders must forcefully enable PowerShell Script Block Logging (Event ID 4104) across the entire enterprise.
Crucially, Script Block Logging operates independently of the AMSI scanning pipeline. Even if an attacker successfully patches AmsiScanBuffer to evade Windows Defender, the underlying PowerShell engine will still diligently log the complete, de-obfuscated content of the malicious script to the Windows Event Log. By centralizing these event logs into a SIEM (Security Information and Event Management) system and actively hunting for known malicious command syntax, defenders maintain a critical layer of visibility and forensic evidence, allowing them to detect and respond to the attack even when AMSI has been defeated.
AMSI Memory Patching represents a pinnacle of low-level evasion techniques utilized by modern cyber adversaries. By manipulating the live memory space of the operating system, attackers bypass one of Microsoft's most critical defensive mechanisms, granting them the ability to execute devastating, fileless malware payloads with complete impunity. Understanding the mechanics of how amsi.dll is located, unprotected, and overwritten is essential for modern security professionals.
Defending against these surgical strikes requires organizations to evolve beyond basic antivirus scanning. By implementing robust architectural controls like Constrained Language Mode to restrict access to critical APIs, deploying advanced EDR solutions capable of detecting memory manipulation anomalies, and maintaining independent visibility through comprehensive Script Block Logging, security teams can effectively disrupt the patching process. By hardening the memory space and scrutinizing process behavior, defenders can neutralize the attacker's ability to operate in the shadows, securing the enterprise against sophisticated fileless threats.
Ready to test your knowledge? Take the AMSI Patching MCQ Quiz on HackCert today!

