Thursday, June 25, 2020

Frida DBI - DeObfuscate PowerShell Script

Frida is a Dynamic Binary Instrumentation (DBI) toolkit that can be used to hook into live processes, analyze various parts of the program and print out debug information including but not limited to getting loaded modules, executed functions, arguments passed to the function etc.

In this blog we'll use "frida-trace", part of Frida toolset to de-obfuscate obfuscated powershell script. When PowerShell loads it get injected with a dll "amsi.dll" that is the core of the "Anti Malware Scan Interface".

"amsi.dll" includes a function called "AmsiScanBuffer" that's called to analyze the powershell scripts executed. Every powershell script that gets executed is initially run through the "AmsiScanBuffer" function that determines whether the script that's to be executed is benign or malicious. If it is malicious the script is terminated and an error is raised. The arguments passed to the "AmsiScanBuffer" from MSDN,



As you can see the 2nd argument that's passed to the function "buffer" contains the buffer that is passed for scanning. "frida-trace"can be used to hook into this function and print out the contents of the "buffer" argument.

"frida-trace" can be run with minimal arguments initially to create a skeleton handler file.


Once you execute the above command you should have a ".js" file created automatically in your python path - "C:\Python36\Scripts\__handlers__\amsi.dll\AmsiScanBuffer.js". You can edit this file to print the necessary argument, in our case argument 1. Argument 1 is a wide string that can be printed on to the console using "log(Memory.readUtf16String(args[1]));"

 
Saving the file will automatically load the script into memory.

Now lets runs an obfuscated powershell script and see if we get de-obfuscated version of it. I took a malicious script from cylance's blog. Running the malicious powershell script in powershell window prints out the de-obfuscated version (which is essentially the 2nd stage of the script) that downloads and runs the final payload. The obfuscated version and de-obfuscated version of the script side by side in the below snapshot.


The complete de-obfuscated script below,


No comments:

Post a Comment