How to deobfuscate JavaScript

Let’s say you have a malicious bit of JavaScript, but you have no idea what it does because it’s been mangled and obfuscated to keep you from finding out.

Step 1

Step one is to try and “beautify” it, make it look nice with a nice layout to see if you can just plain read it. This can be done with a couple of plugins to Notepad++ called JSTool.

Just open up your JS file in Notepad++, and go to plugins > JSTool, and first run JSMin to get rid of any extra crud that’s in there, then run the JSFormat to have it setup nicely in a readable format. Note that this could break the script, so only use it as an initial tool, and don’t use the saved output for subsequent analysis.

Step 2

Step two would be running the actual script, to see if it deobfuscates itself, or in the case of an encrypted payload, decrypts itself. Looking at the beautified version you just made, see if you can spot any deobfuscation/decryption function, and where this is called, then put a breakpoint immediately after it. You do this by simply adding

debugger;

after it (it has to be somewhere in between the script tabs). If you can’t find it, just put the breakpoint at the beginning of the script, then add more as you let the script run.

Open the JS file in Internet Explorer (yes, finally a decent use of that browser!) but don’t let it run the JavaScript (so don’t click allow on the warning that pops up). Hit F12 to get the developer tools to open, and pick the “Debugger” tab. You should now see the source code. Set any additional breakpoints on interesting bits by right-clicking and select “set breakpoint”, then reload the script in Internet Explorer and watch as it breaks on the breakpoint again. Hitting the play button in the debugger lets you step from breakpoint to breakpoint.

You can see the various variables on the right hand side, or if you wan’t to print it, you can go like this in the Console tab:

console.group(variable)

Step 3

You might also want to try and deobfuscate the script with an Interpreter, such as SpiderMonkey. Run it like so:

js -f pat/to/script-file

It might complain over undefined variables, such as the URL (location.href) and others, that the script would normally get from the browser. You can specify these in a file (on REMnux this is in /usr/share/remnux/objects.js) and add any that the script might expect or change the existing ones to match the domain that was expected. In this case the format is like so:

js -f /path/to/objects-file -f /path/to/script-file

You can also try running the script in a small sandbox, like box-js:

box-js /path/to/script-file –download

This will run the script, fake various requests that the script might initiate, and download content requested by the script. It’ll save you the deobfuscated script as it ran, and give you a list of URLs that it interacted with.