🤒AMSI bypass using Python

This article is a demonstration of bypassing AMSI using Python and is heavily influenced from Fluid Attacks blog post by Andres Roldan

The Windows Antimalware Scan Interface (AMSI) is a versatile interface standard that allows your applications and services to integrate with any antimalware product that's present on a machine. AMSI is agnostic of antimalware vendor; it's designed to allow for the most common malware scanning and protection techniques provided by today's antimalware products that can be integrated into applications.

  • AMSI uses two functions AmsiScanString() and AmsiScanBuffer() for checking malicious content.However these two functions are not really different. In fact, AmsiScanString() is a small function which uses AmsiScanBuffer() underneath

  • So, if we can bypass the checks performed by AmsiScanBuffer(), we can also bypass AmsiScanString()

    The AmsiScanBuffer() checks the code and if the parameters passed by the caller code is not valid, it returns an error code E_INVALIDARG

    We can use this and modify the AmsiScanBuffer() function in memory to bypass the anti-malware checking instructions altogether and force it always to return E_INVALIDARG thus bypassing it.

    We can modify the very beginning of AmsiScanBuffer() with the following instructions:

b857000780          mov eax,0x80070057
c3                  ret

That would move the E_INVALIDARG value to EAX, making it the return value of AmsiScanBuffer(),and successfully bypassing it.

Methodology

  1. Get the PID of running powershell.exe processes.

  2. Get a handle for the processes.

  3. Get the loaded modules of the powershell.exe processes.

  4. Find the address in memory of AmsiScanBuffer.

  5. Patch AmsiScanBuffer.

Step 1 : Getting the PID of powershell.exe processes

Code :

Output :

Step 2 : Get a handle for the processes

The handle is an opaque interface to a process.

  • List all the processes along with the user running them

  • Here, we can choose the process svchost with the PID 1832 for our test

Code:

Output:

Step 3 :Get the loaded modules of the powershell.exe processes

Now that we have a handle to a powershell.exe process, we want to retrieve the addresses of the modules to find where amsi.dll is loaded in memory space of the process.

Code:

Output:

Step 4: Find the address in memory of AmsiScanBuffer

Using the discovered base address of amsi.dll, we need to iterate over the memory of the process trying to find the instructions of AmsiScanBuffer.

Code:

Output:

Step 5: Patch AmsiScanBuffer

We can patch the target address with the payload:

Code:

Output:

Final

  • We can chain all the steps and see how it works

Code:

Output:

AmsiScanBuffer is among one of the keywords that are regarded as malicious and can set off an AV. Here, we can see that after running the script we can successfully pass the keyword, bypassing AMSI without triggering the AV.

For more AMSI Bypass methods:

Last updated