Bypassing AMSI

Bypassing the Antimalware Scan Interface (AMSI)

AMSI Bypass

As discussed earlier, AmsiScanBuffer is the function which gets called as soon as a user enters the command in the powersehll.
HRESULT AmsiOpenSession(
[in] HAMSICONTEXT amsiContext,
[out] HAMSISESSION *amsiSession
  • amsiContext: this is the context which is returned from AmsiInitialize function at the time of process creation.
  • amsiSession: This is a session which is created for each command as everytime a new command is issued in powershell, the AmsiOpenSession function gets called.
Bypass Theory
Stage 0 The Key to bypass the AMSI is to somehow crash the amsiSession function, in order to do so we need to look upon the undocumented amsiContext Structure using frida we can easily get the memory address of this structure.
Content of amsiOpenContext
Upon navigating to the memory address using Windows Debugger, it was revealed that first 4 bytes of the Context contains ASCII string AMSI which is same throughout different processes.
Stage 1
Now we know that AmsiContext structure has AMSI in the first four bytes, using this information we will navigate through the AmsiOpenSession function in windows debugger.
Disassembled AmsiOpenSession
It can be seen that RCX register is being compared to the 49534D41 which is nothing else but AMSI in ASCII and next instruction is jump if fail which will return the function with error.
Stage 2
In order to crash the function, we simply need to remove the content of RCX register just before it is compared.
We will place a breakpoint at the amsiOpenSession function and enter any command to trigger the breakpoint
Breakpoint reached
Now zeroing out the value of RCX register in order fail the If condition.
Removing the content of RCX
This will effectively kill the AMSI in powershell process which can be seen below..
AMSI Bypassed
That was the approach to bypass AMSI using Windows Debugger.