In the modern era of cyber defense, the Antimalware Scan Interface (AMSI) stands as one of the most significant hurdles for attackers attempting to execute fileless malware and malicious scripts. Introduced by Microsoft in Windows 10 and Windows Server 2016, AMSI provides a standard interface for applications to send script content and buffers to the installed antivirus or EDR (Endpoint Detection and Response) solution for inspection—regardless of whether the script is obfuscated or loaded directly into memory.
However, as with any security control, threat actors have developed a sophisticated repertoire of techniques to circumvent it. For incident response teams and SOC analysts, understanding how to detect these bypasses using Windows Event Logs is a critical component of a robust endpoint security strategy. This article explores the technical nuances of AMSI, common bypass methods, and the specific forensic artifacts required to identify them within your environment.
The Architecture of AMSI: A Brief Overview
AMSI is not a detection engine itself; rather, it is a bridge. When a script interpreter like PowerShell (System.Management.Automation.dll), VBScript, or JScript receives a command, it sends the de-obfuscated code to the amsi.dll library. This library communicates via RPC with the registered antimalware provider (e.g., Microsoft Defender or a third-party EDR) to determine if the content is malicious.
This architecture is particularly effective against malware analysis evasion techniques like Base64 encoding or XOR encryption. Because the script must eventually be decrypted to be executed by the interpreter, AMSI captures the "cleartext" version at the last possible moment. This falls under the MITRE ATT&CK technique T1059.001 (Command and Scripting Interpreter: PowerShell).
Despite its effectiveness, attackers have realized that if they can disable or corrupt the amsi.dll process within their own session, they can execute malicious code without any inspection. This is where the battle for threat detection begins.
Common AMSI Bypass Techniques
To detect these attacks, we must first understand the "how." Attackers generally target the AMSI mechanism using three primary approaches: memory patching, environment manipulation, and obfuscation.
1. Memory Patching (The "AmsiScanBuffer" Patch)
The most common and effective method involves patching the AmsiScanBuffer function within the amsi.dll loaded in the current process's memory. By overwriting the beginning of this function with instructions that force it to return a "Success" result (specifically AMSI_RESULT_CLEAN), the attacker effectively muzzles the scanner.
Typically, this involves using the Win32 API functions GetProcAddress and WriteProcessMemory (or its .NET equivalents) to change the function's behavior. When a security audit is performed, such as those automated by Secably to identify configuration weaknesses, these types of memory-resident threats are often the primary focus of red teaming exercises.
2. The amsiInitFailed Trick
Early versions of AMSI bypasses relied on a simple logic flaw. By setting a specific internal flag—amsiInitFailed—to true within the AmsiUtils class via .NET reflection, the PowerShell interpreter would assume AMSI failed to initialize and skip all subsequent scanning for that session. While Microsoft has updated PowerShell to make this specific field harder to access, variations using reflection still exist.
3. Environment Variable Hijacking
Attackers can sometimes bypass AMSI by manipulating the environment in which the process starts. For example, setting certain undocumented environment variables can occasionally prevent the AMSI provider from loading correctly, though this is less reliable on modern, fully patched versions of Windows. Understanding these external entry points is a key part of mapping your threat surface, a task that tools like Zondex excel at by discovering exposed services and potential misconfigurations that could facilitate initial access.
Configuring Windows for Maximum Visibility
Standard Windows logging is often insufficient to catch an AMSI bypass. To achieve the level of cybersecurity visibility required for modern threat detection, specific group policies must be enabled.
Enabling PowerShell Script Block Logging (Event ID 4104)
This is the "Holy Grail" of PowerShell forensics. When Script Block Logging is enabled, Windows records the entire content of every script block executed, even if it was de-obfuscated in memory.
- Path: Computer Configuration -> Administrative Templates -> Windows Components -> Windows PowerShell
- Setting: Turn on PowerShell Script Block Logging
- Impact: Generates Event ID 4104 in the
Microsoft-Windows-PowerShell/Operationallog.
Enabling PowerShell Module Logging (Event ID 4103)
While Script Block Logging captures the content, Module Logging captures the execution details and pipeline output. This provides context on how the commands were invoked.
- Path: Computer Configuration -> Administrative Templates -> Windows Components -> Windows PowerShell
- Setting: Turn on Module Logging (Add
*to record all modules)
Analyzing Event Logs for AMSI Bypass Evidence
Once logging is configured, SOC analysts must look for specific patterns within Event ID 4104. Because an AMSI bypass must occur before the main payload is executed, the bypass code itself will often be logged.
Identifying Memory Patching in Logs
Look for script blocks containing references to amsi.dll combined with memory manipulation functions. A classic "one-liner" bypass might look like this in the logs:
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
Or, a more modern memory patch might involve:
$p = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((Get-ProcAddress amsi.dll AmsiScanBuffer), [AmsiScanBufferDelegate])
# ... code to overwrite bytes ...
What to look for:
* AmsiScanBuffer
* amsiInitFailed
* NonPublic,Static
* WriteProcessMemory
* VirtualProtect
* amsi.dll
The Role of Obfuscation
Attackers rarely leave their bypasses in cleartext. They use string concatenation, encoding, or backticks to hide keywords. For example:
"am" + "si" + "Init" + "Failed"
Detection logic must be robust enough to handle these variations. High entropy in script blocks (random-looking strings) or excessive use of special characters is a primary indicator of malicious activity.
Comparison of AMSI Bypass Detection Methods
| Technique | Log Source | Detection Difficulty | Reliability |
|---|---|---|---|
| Simple Reflection | Event 4104 | Low (Keyword based) | High |
| Memory Patching | Event 4104 / EDR | Medium (Requires behavior analysis) | High |
| DLL Unloading | Event 7045 (Service) / Sysmon | High | Medium |
| Obfuscated Wrappers | Event 4104 | Medium (Requires De-obfuscation) | Medium |
Sigma Rules for Proactive Detection
Sigma is an open-source format for writing detection rules that can be converted into SIEM queries (Splunk, ELK, Azure Sentinel). Below is a Sigma rule example designed to detect common AMSI bypass patterns in PowerShell logs.
title: Potential AMSI Bypass via Reflection or Patching
id: 5f2e1a3b-6c4d-4e2a-8f1a-9d8c7b6a5e4f
status: experimental
description: Detects patterns commonly used to bypass the Antimalware Scan Interface (AMSI).
references:
- https://attack.mitre.org/techniques/T1059/001/
author: SAFE Cyberdefense
date: 2023/10/27
logsource:
product: windows
service: powershell
detection:
selection_keywords:
EventID: 4104
ScriptBlockText|contains:
- 'amsiInitFailed'
- 'AmsiScanBuffer'
- 'amsiContext'
- 'amsiSession'
selection_reflection:
ScriptBlockText|contains|all:
- 'GetField'
- 'NonPublic'
- 'Static'
selection_patching:
ScriptBlockText|contains|all:
- 'VirtualProtect'
- 'amsi.dll'
condition: selection_keywords or selection_reflection or selection_patching
falsepositives:
- Administrative scripts (rare)
- Custom security auditing tools
level: high
Real-World Case Study: Emotet’s Evolution
Emotet, one of the most prolific botnets in history, frequently utilized PowerShell-based loaders. In its later iterations, the malware authors realized that AMSI was blocking their initial "stager" scripts. To counter this, they integrated an AMSI bypass directly into the heavily obfuscated macro code of their Word document attachments.
By the time the PowerShell script was launched, the macro had already attempted to patch the memory of the WmiPrvSE.exe or powershell.exe process. For organizations that only monitored for file creation, Emotet was invisible. However, those with incident response procedures centered around Event ID 4104 were able to see the decoded bypass logic right before the connection to the C2 (Command and Control) server was established. This highlights the necessity of endpoint security that goes beyond simple signature matching.
Advanced Detection: Combining Event Logs with Sysmon
While PowerShell logs are essential, they can be bypassed themselves (e.g., by using an older version of PowerShell like version 2.0, which does not support Script Block Logging). To counter this, security professionals should use Sysmon (System Monitor) to augment their data.
Sysmon Event ID 7: Image Loaded
Monitoring for the loading of amsi.dll by unexpected processes can be a sign of injection. More importantly, monitoring for the loading of System.Management.Automation.dll by non-PowerShell processes (like sqlservr.exe or rundll32.exe) can indicate "unmanaged PowerShell" attacks, which often include built-in AMSI bypasses.
Sysmon Event ID 10: ProcessAccess
If an attacker tries to patch AMSI in a different process, Sysmon Event ID 10 will record the access request. Look for processes requesting PROCESS_VM_WRITE or PROCESS_VM_OPERATION rights on a target process.
The Limitations of Log-Based Detection
It is important to acknowledge that logging is a reactive measure. By the time the event is generated, the bypass may have already succeeded. This is why cyber defense must be multi-layered.
- Attack Surface Reduction (ASR): Use Windows Defender ASR rules to block the execution of obfuscated scripts or the creation of child processes by Office applications.
- Constrained Language Mode (CLM): For high-risk users, enforce PowerShell CLM via AppLocker or Windows Defender Application Control (WDAC). This restricts access to the .NET reflection and Win32 API calls required for most AMSI bypasses.
- Removal of PowerShell v2: Ensure that PowerShell v2 is disabled as a Windows Feature to prevent attackers from "downgrading" their way out of logging.
Remediation and Incident Response
When a potential AMSI bypass is detected in your logs, the following steps should be taken immediately:
- Isolate the Host: Prevent the potentially compromised machine from communicating with the rest of the network or external C2 servers.
- Capture Volatile Memory: Before rebooting, capture a memory dump of the suspicious process to confirm if
amsi.dllhas indeed been patched. - Analyze the Script Block: Review the full Event ID 4104 entry. Often, the bypass is just the first line of a much larger malicious script.
- Trace the Parent Process: Use Sysmon or Security Event ID 4688 to find out what launched the script. Was it a scheduled task, a user-initiated command, or a malicious macro?
Implementing a Robust Monitoring Strategy
For a French cybersecurity firm like SAFE Cyberdefense, the focus is always on actionable intelligence. To implement an effective monitoring strategy for AMSI bypasses, follow these steps:
- Audit GPO Coverage: Ensure that Script Block Logging is applied to 100% of your Windows endpoints.
- Centralize Logs: Forward PowerShell logs to a central SIEM. Bypasses are often "noisy" in the logs, but they are easily missed if they remain local to the machine.
- Develop Baselines: Understand what "normal" PowerShell looks like in your environment. Many IT management tools use complex scripts; whitelisting these known-good scripts reduces alert fatigue.
- Automate Response: Use SOAR (Security Orchestration, Automation, and Response) to automatically isolate hosts when a high-confidence AMSI bypass Sigma rule is triggered.
Key Takeaways
- AMSI is a Critical Buffer: It serves as the primary defense against fileless malware and de-obfuscated scripts.
- Bypasses Target Memory: Most bypasses involve patching
AmsiScanBufferinamsi.dllor using .NET reflection to flip internal failure flags. - Logging is Non-Negotiable: PowerShell Script Block Logging (Event ID 4104) is the only way to see the content of bypass scripts that are executed entirely in memory.
- Context Matters: Combine PowerShell logs with Sysmon and Process Tracking (ID 4688) to get a full picture of the attack lifecycle.
- Defense in Depth: Logging should be paired with proactive measures like Constrained Language Mode and Attack Surface Reduction rules to prevent bypasses from occurring in the first place.
By maintaining a rigorous focus on Windows Event Log analysis and staying abreast of the latest bypass techniques, organizations can significantly improve their cyber defense posture. In the arms race between attackers and defenders, visibility remains our most potent weapon. Whether you are conducting a routine malware analysis or responding to an active breach, the artifacts left behind by an AMSI bypass are the clues that lead to the heart of the intrusion.