AMSI Internals: Architecture and Scan Lifecycle
A layer-by-layer analysis of the Antimalware Scan Interface: the Win32 and COM APIs exposed by amsi.dll, provider registration, the Microsoft Defender provider and the life cycle of a scan request, with the telemetry each stage produces.
Introduction
Traditional antimalware engines inspect files: an object is scanned when it is written to disk, opened or executed. That model breaks down with scripting engines and in-memory loaders. The content an engine actually runs can be assembled at run time, downloaded straight into memory or hidden behind several layers of obfuscation that only disappear right before execution.
The Antimalware Scan Interface (AMSI), introduced in Windows 10 and Windows Server 2016,1 closes this gap by inverting the relationship between the application and the security product. The antimalware engine no longer has to guess what an application is about to execute. The application itself, at the points of its execution flow it considers critical, submits the content to whichever antimalware provider is registered on the system. The key property is timing. Content is inspected after the host has de-obfuscated it and before it runs, when it finally appears in clear text.
This article analyzes the AMSI architecture layer by layer, follows a scan request from the calling application to the Microsoft Defender engine and closes with the telemetry and hardening aspects relevant to a defender.
Architecture overview
AMSI is not a single component. It is a chain of layers that a scan request crosses, from the application that generates the content down to the engine that issues the verdict. Figure 1 shows the overall structure.
flowchart TB
subgraph CLIENT["Client process (user mode)"]
direction TB
subgraph APPS["Applications"]
PS["PowerShell"]
WSH["Windows Script Host<br/>(VBScript / JScript)"]
VBA["Office VBA"]
NET[".NET CLR"]
end
subgraph WIN32["Win32 API layer (amsi.dll)"]
FLAT["AmsiScanBuffer()<br/>AmsiScanString()"]
end
subgraph COMAPI["COM API layer (amsi.dll)"]
IAM["IAntimalware::Scan()"]
end
subgraph PROV["AV provider layer (MpOav.dll)"]
IAP["IAntimalwareProvider::Scan()"]
end
PS --> FLAT
WSH --> FLAT
VBA --> FLAT
NET --> FLAT
FLAT --> IAM
IAM --> IAP
end
REG[("Registry<br/>HKLM\SOFTWARE\Microsoft\AMSI\Providers")]
IAM -.->|"provider enumeration"| REG
subgraph SVC["MsMpEng.exe (Microsoft Defender Antivirus service)"]
RPCS["MpSvc.dll<br/>RPC server"]
ENG["mpengine.dll<br/>scan engine"]
RPCS --> ENG
end
IAP <-->|"local RPC"| RPCS
Figure 1. AMSI architecture. Every layer above the RPC channel lives in the address space of the client process.
The main components are summarized in the following table.
| Component | Image | Runs in | Role |
|---|---|---|---|
| AMSI client | e.g. powershell.exe, wscript.exe |
Client process | Generates content and requests the scan |
| AMSI runtime | %SystemRoot%\System32\amsi.dll |
Client process | Exposes the Win32 and COM APIs, loads and invokes providers |
| Defender provider | MpOav.dll |
Client process | Implements IAntimalwareProvider and forwards content to the service |
| Defender service | MsMpEng.exe |
Service process | Hosts the RPC server side (MpSvc.dll) and the engine |
| Scan engine | mpengine.dll |
Service process | Evaluates the content and produces the verdict |
The rest of this section describes each layer in detail.
Applications (AMSI clients)
An AMSI client is any component that calls the AMSI API to submit content for inspection. Microsoft documents the following integrations.
- PowerShell: scripts, interactive use and dynamic code evaluation.
- Windows Script Host (
wscript.exeandcscript.exe), with the JScript and VBScript engines. - User Account Control (UAC): elevation of EXE, COM, MSI or ActiveX installation.
- Windows Management Instrumentation (WMI).
- .NET Framework 4.8 and later: scanning of assemblies, including those
loaded from memory through
Assembly.Load(byte[]), which earlier versions did not scan.3
Microsoft 365 Apps2
- Office VBA macros and JavaScript.
- Excel 4.0 (XLM) macros, whose runtime scanning was added in 2021.4
Office integrations ship with Microsoft 365 Apps, not with Windows, so they are present only where those applications are installed.
Any third-party application can become an AMSI client by calling the public API.
Win32 API layer
The application-facing surface of AMSI is a flat C API, declared in amsi.h,
imported through amsi.lib and implemented by amsi.dll.5 The API
is built around two opaque handles:
HAMSICONTEXT: the AMSI context, created once per application instance and bound to an application name.HAMSISESSION: an optional session that correlates multiple scan requests belonging to the same logical unit of content.
| Function | Purpose |
|---|---|
AmsiInitialize |
Creates the AMSI context for the calling application |
AmsiOpenSession |
Opens a session within a context |
AmsiScanBuffer |
Submits an arbitrary memory buffer for scanning |
AmsiScanString |
Submits a null-terminated wide string for scanning |
AmsiNotifyOperation |
Notifies providers of an arbitrary operation (no session parameter) |
AmsiCloseSession |
Closes a session |
AmsiUninitialize |
Releases the AMSI context |
The flat API is a convenience wrapper. Its job is to translate each call into an invocation of the COM layer below it.
COM API layer
Internally, amsi.dll implements the IAntimalware COM interface (also
declared in amsi.h), which exposes Scan and CloseSession.6
Scan is the dispatch point of the whole architecture:
1
2
3
4
5
HRESULT IAntimalware::Scan(
IAmsiStream *stream, // content to be scanned
AMSI_RESULT *result, // aggregated verdict
IAntimalwareProvider **provider // provider that issued the verdict
);
Content is not passed around as a raw pointer. It is wrapped in an object
implementing IAmsiStream, which exposes two methods:7
GetAttribute: returns metadata about the request, such as the application name (AMSI_ATTRIBUTE_APP_NAME), the content name (AMSI_ATTRIBUTE_CONTENT_NAME), the content size (AMSI_ATTRIBUTE_CONTENT_SIZE) and the session (AMSI_ATTRIBUTE_SESSION).Read: reads the content, or a portion of it, at a given offset.
This abstraction separates the producer of the content from its consumers. A provider can retrieve the metadata it needs and read the content incrementally, without depending on how the client allocated it.
IAntimalware::Scan invokes the registered providers in turn and returns the
verdict together with a reference to the provider that issued it.
Provider registration
AMSI providers are in-process COM servers.8 Their registration takes two parts:
- AMSI registration: a subkey named after the provider CLSID under
HKLM\SOFTWARE\Microsoft\AMSI\Providers\{CLSID}. - COM registration: the standard class registration under
HKLM\SOFTWARE\Classes\CLSID\{CLSID}\InprocServer32, whose default value holds the path of the provider DLL. The class must use theBoththreading model.
When the AMSI context is created, amsi.dll enumerates the first key, resolves
each CLSID through the second and loads the corresponding DLLs into the client
process.
Starting with Windows 10, version 1903, AMSI can require provider DLLs to be
Authenticode-signed before loading them. The check is disabled by default and
is controlled by the FeatureBits REG_DWORD value under
HKLM\SOFTWARE\Microsoft\AMSI: 0x1 (the default, also assumed when the value
is absent) disables the check, 0x2 enables it.9
Experiment: enumerating registered AMSI providers
The following PowerShell snippet lists the registered providers and resolves the DLL that implements each of them.
1 2 3 4 5 6 7 8 Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\AMSI\Providers' | ForEach-Object { $clsid = $_.PSChildName $server = Get-ItemProperty "Registry::HKEY_CLASSES_ROOT\CLSID\$clsid\InprocServer32" -ErrorAction SilentlyContinue [pscustomobject]@{ CLSID = $clsid Server = $server.'(default)' } }On a system protected by Microsoft Defender Antivirus, the output contains the CLSID
{2781761E-28E0-4109-99FE-B9D127C57AFE}, implemented byMpOav.dllunder%ProgramData%\Microsoft\Windows Defender\Platform\<version>\.
AV provider layer
Each provider implements the IAntimalwareProvider interface:9
| Method | Purpose |
|---|---|
Scan(IAmsiStream *stream, AMSI_RESULT *result) |
Inspects the content and returns a verdict |
CloseSession(ULONGLONG session) |
Releases any per-session state the provider keeps |
DisplayName(LPWSTR *displayName) |
Returns a human-readable provider name |
For Microsoft Defender Antivirus, the provider is MpOav.dll. It does not scan
the content itself. Its job is to marshal the request across the process
boundary to the Defender service.
RPC layer and the Defender service
MpOav.dll forwards each request over local RPC to MsMpEng.exe, the
Microsoft Defender Antivirus service process. Inside the service, the RPC
server side (MpSvc.dll) receives the request and hands the content to the
scanning engine, mpengine.dll, which evaluates it with signatures, emulation
and heuristics. The verdict travels back along the same path.
The process boundary
Figure 1 makes an architectural property explicit that has direct
consequences for threat modeling: the client, the AMSI runtime and the
provider all share the same address space. The only process boundary in
the chain sits between the in-process provider and MsMpEng.exe.
Experiment: observing AMSI components in a client process
In a PowerShell session, list the AMSI-related modules loaded in the current process:
1 2 3 (Get-Process -Id $PID).Modules | Where-Object ModuleName -match '^(amsi|MpOav)\.dll$' | Select-Object ModuleName, FileNameBoth
amsi.dllandMpOav.dllshow up as modules ofpowershell.exe. The same result can be observed in Process Explorer (View → Lower Pane View → DLLs).
As a consequence, the integrity of the AMSI channel can be no stronger than the integrity of the client process. Code already running inside the process with the same privileges can, in principle, interfere with it. This is consistent with Microsoft’s servicing criteria, under which components are not security boundaries unless explicitly named as such, and AMSI is not named.10 Microsoft also notes that the AMSI APIs are designed to work with non-protected processes.8 AMSI should therefore be treated as a visibility mechanism, not as a security boundary. The defensive value it provides must be preserved through complementary telemetry and tamper detection, discussed later in this article.
Life cycle of a scan request
From the client’s point of view, every interaction with AMSI follows the same four phases: initialization, scanning, evaluation of the result and release. Figure 2 shows the full sequence, including the internal hops described in the previous section.
sequenceDiagram
autonumber
participant App as Application
participant AMSI as amsi.dll
participant Prov as MpOav.dll (provider)
participant Svc as MsMpEng.exe
Note over App,AMSI: Initialization
App->>AMSI: AmsiInitialize(appName, &amsiContext)
AMSI->>AMSI: Enumerate and load registered providers
App->>AMSI: AmsiOpenSession(amsiContext, &session)
Note over App,Svc: Scanning
App->>AMSI: AmsiScanBuffer(amsiContext, buffer, length, contentName, session, &result)
AMSI->>Prov: IAntimalwareProvider::Scan(stream, &result)
Prov->>Svc: Scan request (local RPC)
Svc-->>Prov: Verdict
Prov-->>AMSI: AMSI_RESULT
AMSI-->>App: AMSI_RESULT
Note over App: Evaluation
App->>App: AmsiResultIsMalware(result)
Note over App,AMSI: Release
App->>AMSI: AmsiCloseSession(amsiContext, session)
App->>AMSI: AmsiUninitialize(amsiContext)
Figure 2. Life cycle of an AMSI scan request.
Initialization
1
2
HRESULT AmsiInitialize(LPCWSTR appName, HAMSICONTEXT *amsiContext);
HRESULT AmsiOpenSession(HAMSICONTEXT amsiContext, HAMSISESSION *amsiSession);
AmsiInitialize creates the context and binds it to appName. Providers
receive this name as the AMSI_ATTRIBUTE_APP_NAME attribute of every request,
and it also appears in the telemetry. A client normally initializes AMSI once
and reuses the context for its whole lifetime.
AmsiOpenSession is optional, but its semantics matter. A session lets
antimalware vendors correlate different scan requests, so that different
fragments of a malicious payload can be associated.1 A script engine that
de-obfuscates code in stages, as PowerShell does, can submit each intermediate
fragment under the same session. A provider can then correlate fragments that
look harmless individually but are malicious in combination.
Scanning
1
2
3
4
5
6
7
8
HRESULT AmsiScanBuffer(
HAMSICONTEXT amsiContext,
PVOID buffer, // content to scan
ULONG length, // size of the content, in bytes
LPCWSTR contentName, // file name, URL or other identifier (optional)
HAMSISESSION amsiSession, // session handle (optional)
AMSI_RESULT *result // verdict
);
contentName is optional but valuable. It identifies where the content came
from (for example the path of a script) and is propagated both to the
providers and to the telemetry. AmsiScanString is equivalent but accepts a
null-terminated wide string instead of a buffer and a length.
The return value and the verdict are two separate things. A successful
HRESULT only means the scan took place. The verdict is the value stored
in *result.
Evaluating the result
AMSI_RESULT is an ordered enumeration. Microsoft documents that any result
equal to or larger than 32768 (0x8000) is considered malware.11
The numeric values below come from amsi.h:
| Value | Constant | Meaning |
|---|---|---|
0 |
AMSI_RESULT_CLEAN |
Known good: no detection, and the result is unlikely to change after a future definition update |
1 |
AMSI_RESULT_NOT_DETECTED |
No detection, but the result might change after a future definition update |
0x4000–0x4FFF |
AMSI_RESULT_BLOCKED_BY_ADMIN_START … _END |
Blocked by administrative policy |
0x8000 |
AMSI_RESULT_DETECTED |
Malware detected |
Clients should use the macros in amsi.h rather than compare values directly.
AmsiResultIsMalware(r), documented by Microsoft, evaluates to true for
r >= AMSI_RESULT_DETECTED. AmsiResultIsBlockedByAdmin(r), which checks the
administrative range, is defined in the header but has no documentation page. The decision to block is up to the client. AMSI
reports the verdict, and the application enforces it.
Release
1
2
void AmsiCloseSession(HAMSICONTEXT amsiContext, HAMSISESSION amsiSession);
void AmsiUninitialize(HAMSICONTEXT amsiContext);
AmsiCloseSession lets providers discard per-session state through
IAntimalwareProvider::CloseSession. AmsiUninitialize releases the context
and the providers loaded for it.
A minimal AMSI client
The following program walks through the whole life cycle and submits a buffer for inspection.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <windows.h>
#include <amsi.h>
#include <stdio.h>
#pragma comment(lib, "amsi.lib")
int wmain(void)
{
HAMSICONTEXT context = NULL;
HAMSISESSION session = NULL;
AMSI_RESULT result = AMSI_RESULT_CLEAN;
HRESULT hr;
const char content[] = "Write-Output 'Hello from an AMSI client'";
hr = AmsiInitialize(L"InternalsDemo", &context);
if (FAILED(hr)) {
wprintf(L"AmsiInitialize failed: 0x%08lX\n", hr);
return 1;
}
hr = AmsiOpenSession(context, &session);
if (FAILED(hr)) {
wprintf(L"AmsiOpenSession failed: 0x%08lX\n", hr);
AmsiUninitialize(context);
return 1;
}
hr = AmsiScanBuffer(context,
(PVOID)content,
(ULONG)(sizeof(content) - 1),
L"demo.ps1",
session,
&result);
if (SUCCEEDED(hr)) {
wprintf(L"AMSI_RESULT = 0x%X (malware: %s)\n",
result,
AmsiResultIsMalware(result) ? L"yes" : L"no");
} else {
wprintf(L"AmsiScanBuffer failed: 0x%08lX\n", hr);
}
AmsiCloseSession(context, session);
AmsiUninitialize(context);
return 0;
}
Telemetry
AMSI is valuable to a defender not only because of the verdicts it produces but also because of the signals it leaves behind. Three sources are particularly relevant.
The AMSI ETW provider
amsi.dll emits an event for every scan request through the
Microsoft-Antimalware-Scan-Interface ETW provider
({2A576B87-09A7-520E-C21A-4942F0271D67}). Event ID 1101 carries, among
other fields, the application name, the content name, the scan result and the
scanned content itself. This is the de-obfuscated form of the content,
the same one the provider evaluated.
Experiment: capturing an AMSI trace
From an elevated prompt, start a trace session that logs to a file, generate some activity in a new PowerShell window, then stop the session and decode the events:
1 2 3 4 5 6 7 logman start AMSITrace -p Microsoft-Antimalware-Scan-Interface Event1 -o AMSITrace.etl -ets # ... run some PowerShell commands in another window ... logman stop AMSITrace -ets Get-WinEvent -Path .\AMSITrace.etl -Oldest | Where-Object Id -eq 1101 | Select-Object TimeCreated, @{ n = 'Fields'; e = { $_.Properties.Value } }To observe a detection without handling real malware, use the standard AMSI test sample, which Microsoft Defender detects through a dedicated test signature.12
Because the trace includes the scanned content, it can contain sensitive information such as credentials passed on a command line. Collection and retention policies should account for this.
Microsoft Defender events
When the verdict is a detection, Microsoft Defender Antivirus records it in the
Microsoft-Windows-Windows Defender/Operational channel: event ID 1116
(MALWAREPROTECTION_STATE_MALWARE_DETECTED) for the detection and 1117
(MALWAREPROTECTION_STATE_MALWARE_ACTION_TAKEN) for the action
taken.13 AMSI-originated
detections can be told apart by their resource path, which refers to AMSI
rather than to a file on disk.
Complementary sources
AMSI telemetry is most effective when it is correlated with other sources that observe the same activity from a different vantage point:
- PowerShell Script Block Logging records script blocks independently of
AMSI, as event ID
4104. Windows PowerShell 5.1 writes it toMicrosoft-Windows-PowerShell/Operational; PowerShell 7 uses the same event ID in thePowerShellCore/Operationalchannel.14 - Image load events (Sysmon event ID
7, disabled by default) show which processes loadamsi.dlland the provider DLLs.15 - Registry auditing of
HKLM\SOFTWARE\Microsoft\AMSI\Providersand of theInprocServer32keys of registered providers (Sysmon event IDs12,13and14: key create/delete, value set, key and value rename) shows changes to the provider configuration.15
Hardening considerations
The architectural analysis translates into a few concrete recommendations:
- Protect the provider configuration. Adding, removing or redirecting a
provider changes what AMSI loads into every client process. Treat any change
under the
AMSI\Providerskey, or to theInprocServer32path of a registered provider, as a high-severity event. Enable Microsoft Defender Tamper Protection to protect the Defender configuration. - Enforce provider signing. Setting
FeatureBitsto0x2makes AMSI load only Authenticode-signed provider DLLs.9 - Remove downgrade paths. Windows PowerShell 2.0 predates the security
features of Windows PowerShell 5.x, AMSI protection among
them.16 It was deprecated in Windows 10, version 1709, and
removed from Windows 11, version 24H2 (August 2025) and Windows Server 2025
(September 2025).17 On older systems, disable the
MicrosoftWindowsPowerShellV2optional feature (PowerShell-V2on Windows Server).16 - Combine AMSI with application control. App Control for Business (WDAC) and PowerShell Constrained Language Mode limit what code can run in the first place, so the system’s security does not rest on AMSI’s verdicts alone.
- Monitor for loss of visibility. Because AMSI runs in-process, the absence of expected telemetry is itself a signal. Script hosts that run code but produce no AMSI events, or that unexpectedly stop producing them, should be investigated.
Summary
AMSI shifts antimalware inspection from the file system to the point of
execution. A client submits content through the flat API in amsi.dll. The
request is dispatched through IAntimalware to every provider registered under
HKLM\SOFTWARE\Microsoft\AMSI\Providers, and for Microsoft Defender it crosses
the process boundary via local RPC to MsMpEng.exe, where mpengine.dll
issues the verdict. All layers up to the provider share the client’s address
space. That property defines both the strength of AMSI (visibility into
de-obfuscated content) and its limit (its integrity depends on the client
process), and it is why AMSI telemetry should always be correlated with
independent sources.
References
-
Microsoft Learn, Antimalware Scan Interface (AMSI). ↩︎ ↩︎2 ↩︎3
-
Microsoft Learn, Anti-malware Scan Interface Integration with Microsoft Defender Antivirus. ↩︎ ↩︎2
-
.NET Blog, Announcing the .NET Framework 4.8. ↩︎
-
Microsoft Security Blog, XLM + AMSI: New runtime defense against Excel 4.0 macro malware, March 3, 2021. ↩︎
-
Microsoft Learn, amsi.h header. Function signatures checked against
amsi.hin the Windows SDK 10.0.26100.0. ↩︎ -
Microsoft Learn, IAntimalware interface and IAntimalware::Scan. ↩︎
-
Microsoft Learn, IAmsiStream interface and AMSI_ATTRIBUTE enumeration. ↩︎
-
Microsoft Learn, Developer audience, and sample code. ↩︎ ↩︎2
-
Microsoft Learn, IAntimalwareProvider interface. ↩︎ ↩︎2 ↩︎3
-
Microsoft Security Response Center, Windows Security Servicing Criteria. ↩︎
-
Microsoft Learn, AMSI_RESULT enumeration. ↩︎
-
Microsoft Learn, How AMSI helps you defend against malware. ↩︎
-
Microsoft Learn, Microsoft Defender Antivirus event IDs and error codes. ↩︎
-
Microsoft Learn, about_Logging (Windows PowerShell 5.1). ↩︎
-
PowerShell Team Blog, Windows PowerShell 2.0 Deprecation. ↩︎ ↩︎2
-
Microsoft Support, PowerShell 2.0 removal from Windows. ↩︎