Listen to this Post

Introduction:
Antimalware Scan Interface (AMSI) is a critical security component that allows applications and services to integrate with any antimalware product on Windows. Traditional AMSI bypasses rely on patching `AmsiScanBuffer` in memory—a technique easily flagged by endpoint detection systems. A more sophisticated, patchless evasion method leverages Windows Page Guard exceptions and Vectored Exception Handlers (VEH) to manipulate execution flow without altering a single byte, rendering static and behavioral detections significantly less effective.
Learning Objectives:
- Understand how Windows Page Guard memory protection triggers exceptions and how Vectored Exception Handlers can intercept them.
- Implement a patchless AMSI bypass targeting `AmsiScanBuffer` using a custom VEH and memory manipulation techniques.
- Identify detection strategies and hardening measures to defend against VEH-based evasion in enterprise environments.
You Should Know:
- Understanding Page Guard Exceptions and Vectored Exception Handlers
Page Guard is a memory protection flag (PAGE_GUARD) that generates a `STATUS_GUARD_PAGE_VIOLATION` exception when a memory page is accessed. Vectored Exception Handlers are user-mode callbacks registered via `AddVectoredExceptionHandler` that can handle these exceptions before the system’s structured exception handling. In a patchless AMSI bypass, an attacker sets a Page Guard on the `AmsiScanBuffer` function’s memory region. When AMSI attempts to scan PowerShell content, the guard triggers an exception. The VEH, registered beforehand, intercepts this exception and redirects execution to a benign return value (e.g., AMSI_RESULT_CLEAN) without ever patching the function.
Step‑by‑step guide:
- Locate `AmsiScanBuffer` address – Use `GetProcAddress` on `amsi.dll` after loading it.
- Change memory protection – Use `VirtualProtect` to add `PAGE_GUARD` to the first byte(s) of
AmsiScanBuffer. - Register VEH – Call `AddVectoredExceptionHandler` with a handler function that checks for
STATUS_GUARD_PAGE_VIOLATION. - Inside the VEH – When exception occurs, modify the thread context (e.g., set return register `EAX/RAX` to `AMSI_RESULT_CLEAN` = 0) and skip original function execution.
- Execute PowerShell – Any PowerShell script will now bypass AMSI scanning.
Example PowerShell (conceptual, demonstrating the logic):
Load amsi.dll $amsi = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer( (Get-ProcAddress kernel32!LoadLibrary), <a href="...">Type</a> ) Simplified: use pinvoke or C to register VEH and set PAGE_GUARD Actual implementation requires C/C++ or .NET with unsafe code.
Windows / Linux note: This technique is Windows‑specific. On Linux, similar concepts apply to `LD_PRELOAD` or seccomp bypasses but not directly analogous.
2. Crafting a Proof‑of‑Concept VEH Handler in C
To operationalize the bypass, a VEH handler must be written in C/C++ and compiled into a DLL or executable. The handler inspects the exception record and modifies the context to force `AmsiScanBuffer` to return AMSI_RESULT_CLEAN.
Step‑by‑step guide:
- Define exception handler – Handler function with signature
LONG WINAPI VectoredHandler(PEXCEPTION_POINTERS ExceptionInfo). - Check exception code – Verify `ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION` and that the faulting address belongs to
AmsiScanBuffer. - Modify context – Set `ContextRecord->Rax` (x64) or `ContextRecord->Eax` (x86) to 0 (
AMSI_RESULT_CLEAN). Then set `ContextRecord->Rip` to the next instruction (or a `ret` stub). - Remove guard page – Call `VirtualProtect` to remove `PAGE_GUARD` so the exception doesn’t repeat (optional – can be handled per invocation).
- Return `EXCEPTION_CONTINUE_EXECUTION` – Execution resumes with spoofed return value.
Example handler snippet:
LONG WINAPI AmsiBypassVEH(PEXCEPTION_POINTERS ExceptionInfo) {
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) {
PCONTEXT ctx = ExceptionInfo->ContextRecord;
ctx->Rax = 0; // AMSI_RESULT_CLEAN
ctx->Rip += 0x05; // Skip prologue (simplified)
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
- Deploying the Bypass in a Red Team Engagement
Once the VEH is registered and the Page Guard is set, any PowerShell invoked in the same process will see `AmsiScanBuffer` return clean, effectively disabling AMSI. This technique is “patchless” – no byte modifications, so memory scanners looking for classic patches (0xB8 0x57 0x00 0x07 0x80) will miss it.
Step‑by‑step deployment:
- Inject the handler – Load the compiled VEH DLL into a target PowerShell process (e.g., via `CreateRemoteThread` or using reflective loading).
- Register VEH inside target process – Execute
AddVectoredExceptionHandler(1, AmsiBypassVEH). - Apply Page Guard – Call `VirtualProtect` on `AmsiScanBuffer` with
PAGE_EXECUTE_READWRITE | PAGE_GUARD. - Trigger AMSI – Run any PowerShell command, e.g.,
Invoke-Mimikatz. The VEH intercepts and bypasses detection. - Clean up – Remove the VEH (
RemoveVectoredExceptionHandler) and restore original memory protection to avoid instability.
Windows commands to test:
:: Check AMSI status (before bypass)
powershell -Command "[bash].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)"
:: After VEH bypass, this should not trigger AMSI
powershell -Command "Invoke-Expression 'Write-Host Bypassed'"
4. Detection and Mitigation Strategies
Security products can detect VEH‑based attacks by monitoring for newly registered vectored handlers that point to writable or unusual memory regions. Additionally, the `PAGE_GUARD` modification on critical AMSI functions can be flagged as anomalous.
Step‑by‑step hardening:
- Hook `AddVectoredExceptionHandler` – Use EDR user‑mode hooks to inspect handler callbacks; if a handler resides outside signed modules, block it.
- Scan for `PAGE_GUARD` on AMSI functions – Periodically enumerate memory protections of `amsi.dll` sections; alert on
PAGE_GUARD. - Deploy kernel‑callbacks – Use `PsSetCreateProcessNotifyRoutineEx` and `ObRegisterCallbacks` to monitor and block process injection attempts that could install VEH.
- Enable AMSI logging – Configure PowerShell logs (Group Policy:
Turn on PowerShell Script Block Logging) to capture all script content even if AMSI returns clean. - Use AMSI providers with callstack analysis – Advanced EDRs check the caller of
AmsiScanBuffer; if the caller is a VEH dispatcher, treat as suspicious.
PowerShell logging command:
Enable script block logging (requires admin) Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1
5. Advanced Variations: Linux and Cross‑Platform Parallels
Though AMSI is Windows‑only, the concept of patchless evasion via exception handlers has analogues on Linux. For example, using `sigaction` with `SA_SIGINFO` to handle segmentation faults caused by memory protection changes (mprotect with PROT_NONE) can similarly redirect execution in security tools like libseccomp.
Step‑by‑step Linux concept:
- Set memory protection – Use `mprotect` on a target function (e.g., `strcmp` used by a security monitor) to
PROT_NONE. - Install signal handler – Register handler for `SIGSEGV` that modifies the context (ucontext_t) to skip the function and return a success value.
- Execute monitored code – The function call triggers a segfault, handler bypasses the check.
Example Linux C snippet:
include <signal.h>
include <sys/mman.h>
void segv_handler(int sig, siginfo_t si, void uctx) {
ucontext_t uc = uctx;
uc->uc_mcontext.gregs[bash] = 0; // Return 0 (success)
uc->uc_mcontext.gregs[bash] += 2; // Skip call
}
// Then: mprotect((void)target_func, pagesz, PROT_NONE);
// And: sigaction(SIGSEGV, &sa, NULL);
This cross‑platform insight shows that exception‑driven bypasses are a universal evasion paradigm.
- Mitigating VEH Abuse via ETW and Kernel‑Mode Monitoring
Windows Event Tracing for Windows (ETW) provides telemetry on exception dispatching. By enabling `Microsoft-Windows-Kernel-Process` and `Microsoft-Windows-Exception` providers, defenders can detect rapid sequential guard page violations on the same module. Additionally, kernel‑mode callbacks (PsSetLoadImageNotifyRoutine) can monitor when `amsi.dll` is loaded and verify its integrity.
Step‑by‑step detection using ETW:
- Start ETW session – `logman start “AMSI-Monitor” -p “Microsoft-Windows-Exception” 0x1 -o detection.etl -ets`
2. Analyze events – Look for `Event ID 1000` (exception dispatch) with `ExceptionCode` = `0x80000001` (STATUS_GUARD_PAGE_VIOLATION) and module name =amsi.dll. - Correlate with process creation – If a non‑debugging process (like PowerShell) triggers multiple guard page exceptions on AMSI, alert.
Windows command to query ETW events:
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Exception/Operational'; ID=1000} | Where-Object { $<em>.Message -like "0x80000001" -and $</em>.ProcessName -eq "powershell.exe" }
What Undercode Say:
- Patchless doesn’t mean undetectable – While VEH bypasses avoid byte‑patching signatures, they introduce behavioral anomalies (guard page exceptions, new VEH registrations) that advanced EDRs can catch.
- Defense in depth with logging – Enabling PowerShell Script Block Logging and ETW exceptions telemetry provides visibility even when AMSI returns clean; never rely solely on AMSI as a primary control.
The hack’s brilliance lies in abusing a legitimate Windows exception mechanism to subvert AMSI without touching its code. However, it also underscores a recurring theme: security controls that assume linear execution flow are vulnerable to exception‑orchestrated redirection. Future EDR solutions will likely incorporate VEH registration hooks and guard page anomaly scoring. For red teams, this technique remains potent against legacy AV; for blue teams, invest in kernel‑callbacks and AMSI provider chaining to catch both known and unknown bypass patterns.
Prediction:
As Microsoft continues hardening AMSI—potentially by embedding it into the .NET runtime or blocking user‑mode VEH registration for security‑sensitive processes—attackers will pivot to kernel‑level exception handlers or hardware breakpoints (e.g., DR0-DR3). Within 12–18 months, expect open‑source tooling to automate patchless AMSI bypasses across all major EDRs, pushing defenders toward behaviour‑based detection models that correlate exception rates with process lineage. Eventually, Microsoft may introduce a “protected AMSI” region that disallows `PAGE_GUARD` modifications, but legacy Windows systems will remain vulnerable indefinitely.
▶️ Related Video (78% Match):
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Abelousova Patchless – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


