Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / Web attacks

Lab · Easy · 1 hour

JavaScript Deobfuscation

Reverse obfuscated JavaScript safely: beautify, resolve a string array, and intercept eval to read a payload without running it.

  • javascript
  • deobfuscation
  • reverse-engineering
  • client-side
On this page 11 sections
  1. ·Prerequisites
  2. ·Lab setup
  3. 1Build the lab target
  4. 2Triage the file before reading it
  5. 3Beautify without executing
  6. 4Pull the real strings out of the decoy array
  7. 5Build a packed sample, then intercept eval instead of running it
  8. 6Recover the original logic and confirm it
  9. 7Detect and defend
  10. ·Check
  11. ·Clean up

Obfuscation hides the shape of a script without changing what it does. Attackers use it to smuggle credit-card skimmers past code review, and to disguise malware inside npm packages. Here you obfuscate a tiny script you wrote yourself, then read it back as an analyst would: beautify it, pull the real strings from a decoy array, and intercept eval so the payload prints instead of runs.

What You'll Learn

  • Recognise the string-array and eval-wrapper patterns that obfuscation tools produce
  • Beautify obfuscated JavaScript without running it
  • Tell a real string apart from decoy filler inside an obfuscated array
  • Intercept eval to reveal a decoded payload safely, instead of executing it
  • Recover the original logic and a hidden value from a file you obfuscated yourself
  • Explain how a defender spots obfuscated JavaScript in logs, proxies and code review

Prerequisites

This lab assumes the fundamentals from JavaScript Basics: variables, functions, and how node runs a script. Work through that workbook first if any of that is new.

You do not need prior reverse-engineering experience. You reverse two patterns here: a string moved into an array, and code hidden behind eval. The same two patterns show up again in Cross-Site Scripting (XSS) and Advanced XSS & CSRF. There, an attacker payload is often obfuscated to dodge a simple keyword filter.

Lab setup

  • A Linux, macOS or WSL shell with Node.js (v18 or newer) and npm. Check with node --version.
  • Internet access the first time you use npx to fetch two public npm packages: javascript-obfuscator (builds the lab target) and js-beautify (reformats it). Run npx <package> --help first if you want the full option list before using a flag this lab does not cover.
  • No external target and no third party. You write a small script, obfuscate it yourself, then deobfuscate your own file. You own every byte you analyse.

Only run or eval obfuscated JavaScript that you wrote yourself or were given for this lab. In a real engagement or incident, treat obfuscated JavaScript you did not write as hostile. Read it statically first. Only run it, if at all, inside an isolated sandbox with no network and no credentials. This lab builds the read-only habit that professional analysts rely on.

Step 1: Build the lab target

Create a working directory and a small, deliberately simple script. It stands in for the kind of logic obfuscation is used to hide: a check against a secret value.

1

Write the source, then obfuscate it

You play both roles here: the developer who writes the script, and the analyst who later has to read it without the source. Keep the two files separate so Step 6 can prove you recovered the right logic.

mkdir -p ~/labs/js-deob && cd ~/labs/js-deob
cat > original.js <<'EOF'
function checkLicense(key) {
  const validKey = "KR{d30bfuscate_the_js}";
  if (key === validKey) {
    console.log("License valid.");
    return true;
  }
  console.log("License invalid.");
  return false;
}
checkLicense(process.argv[2] || "");
EOF
npx javascript-obfuscator original.js --output target.js
cp original.js original.js.answer   # set the answer aside; do not read it until Step 6
rm original.js
ls -la
# Example output
-rw-r--r-- 1 kali kali  246 Nov 18 10:02 original.js.answer
-rw-r--r-- 1 kali kali 1399 Nov 18 10:02 target.js

target.js is now your lab target: 246 bytes became almost 1.4 KB. That size jump is the first sign of obfuscation, and you see it before you read a single line.

Step 2: Triage the file before reading it

2

Measure the file and flag its tells

A tester never opens an unknown JavaScript file straight into an editor and starts running bits of it. Check size, line count and keywords first.

wc -l -c target.js
grep -c "eval\|Function(" target.js
grep -oE "_0x[0-9a-f]+" target.js | sort -u | wc -l
# Example output — your counts will differ slightly run to run, because
# javascript-obfuscator randomises identifiers and array order every time
0 1399 target.js
0
17

The whole file is one line of 1.4 KB, and it uses 17 distinct hex-style identifiers (_0x...) instead of normal variable names. That is the classic shape of a string-array obfuscator: everything readable has been moved into data and given a meaningless name. No eval here, so this sample hides its strings in a plain array, not behind a self-decoding blob — that pattern comes in Step 5.

Step 3: Beautify without executing

3

Restore formatting, change nothing else

Beautifying only re-indents and re-wraps the file. It does not rename anything and it never runs any code — it is always the safe first move.

npx js-beautify target.js > target.beautified.js
wc -l target.beautified.js
# Example output
35 target.beautified.js

Open target.beautified.js in an editor now. One line became about 35. You can see statement boundaries and matching braces, even though most names are still meaningless.

Step 4: Pull the real strings out of the decoy array

4

Find the array and separate signal from noise

Most JavaScript obfuscators move every string literal in the program into one array. They then pad the array with junk entries, so a casual read does not reveal which strings matter.

grep -oE "'[^']*'" target.beautified.js | sort -u
# Example output — exact values match (strings are not re-encoded by default),
# but the mix of real and junk entries you get can differ in order
'10SlCTij'
'216686iZcnPF'
'2422aVqTmo'
'2FVlHJy'
'324mVYvdt'
'3549710YSdkBW'
'4569264WKffmC'
'4806mjLlsb'
'5682591HEOuer'
'6735729vqvvjY'
'8493sNLCrJ'
'8NolYsL'
'KR{d30bfuscate_the_js}'
'License\x20invalid.'
'License\x20valid.'
'argv'
'log'

Twelve of these are junk: short runs of digits glued to random letters (5682591HEOuer, 8NolYsL), used only to pad the array and confuse a quick skim. The remaining five are real program strings, and one of them — KR{d30bfuscate_the_js} — is the secret the script compares your input against. You read it straight out of the array literal, as plain data, without running the program's logic at all.

This worked because the default obfuscation profile does not re-encode the string values — it only shuffles their position and name. A sample in the wild may encode its strings: base64, hex escapes, or a custom cipher. Decode each candidate string on its own with node -e. Check the result before you trust it. Never feed a candidate string to eval.

Step 5: Build a packed sample, then intercept eval instead of running it

String-array obfuscation hides data. The other common pattern, seen in web skimmers and malicious npm packages, hides a whole second program behind eval. Build a tiny, harmless example of that shape to practise the safe way to read it.

5

Pack a payload, then redirect eval to the console

Never let eval run code you cannot already read. Overriding the global eval with a function that only prints its argument gives you the decoded payload without running it, because the real payload never executes.

cd ~/labs/js-deob
PAYLOAD_B64=$(node -e "console.log(Buffer.from('console.log(\"hello from the payload\")').toString('base64'))")
echo "eval(Buffer.from(\"$PAYLOAD_B64\", \"base64\").toString());" > packed.js
cat packed.js
# Example output
eval(Buffer.from("Y29uc29sZS5sb2coImhlbGxvIGZyb20gdGhlIHBheWxvYWQiKQ==", "base64").toString());

In a browser, the same pattern reads eval(atob("...")) — atob is the browser's base64 decoder. This lab uses Buffer.from(str, "base64") instead, which does the same job and is guaranteed to exist in any Node version.

Now read packed.js without ever letting its decoded contents run:

node -e "global.eval = (code) => { console.log('--- decoded payload ---'); console.log(code); }; require('./packed.js');"
# Example output
--- decoded payload ---
console.log("hello from the payload")

The real payload — console.log("hello from the payload") — is now on your screen in plain text, and it never executed. This is the core safe-analysis technique: redirect the interpreter's own decode-and-run step into a print statement, and read the output instead of trusting it.

Step 6: Recover the original logic and confirm it

6

Put the pieces back together

You have the real string values from Step 4. Write out the plain-language version of target.js, then confirm it behaves exactly like the source you never looked at.

checkLicense(key):
  if key equals "KR{d30bfuscate_the_js}":
    print "License valid." and return true
  else:
    print "License invalid." and return false

Confirm it by running the obfuscated file with the value you recovered, and comparing it against the answer file you set aside in Step 1:

node target.js "KR{d30bfuscate_the_js}"
diff <(node target.js "KR{d30bfuscate_the_js}") <(node original.js.answer "KR{d30bfuscate_the_js}")
# Example output
License valid.

An empty diff confirms the obfuscated file and the original behave identically for the value you recovered by reading, not by guessing.

Step 7: Detect and defend

7

See this from the defender's side

Every pattern you just reversed by hand leaves signals a defender can act on before an analyst is ever needed.

  • Content-Security-Policy. A CSP without 'unsafe-eval' stops a browser from running an eval-packed payload at all, no matter how well it is hidden.
  • Proxy and EDR telemetry. A web proxy or endpoint agent that logs outbound JavaScript can flag a high ratio of _0x-style identifiers to normal words. It can also flag a single oversized string literal feeding eval or Function.
  • Static scanning in code review and CI. Tools such as semgrep ship rules that match eval( combined with a decode call (atob, Buffer.from(...,'base64')) on the same line. That is the exact shape you built in Step 5.
  • Dependency scanning. Obfuscated code inside a third-party npm package, rather than your own source, is itself a red flag. A sudden jump in a dependency's minified size between versions is worth a diff.

None of these defences need to deobfuscate anything. They act on the shape of obfuscation — size, identifier noise, and the eval-plus-decode pattern — which is far cheaper than reading every byte by hand.

Check

You have finished this lab when you can show:

  1. The recovered literal KR{d30bfuscate_the_js}, read out of target.js without running its real logic (Step 4).
  2. The decoded payload text from packed.js, obtained with eval intercepted and never actually run (Step 5).
  3. An empty diff between target.js and original.js.answer when both are run with the value you recovered (Step 6).

Clean up

cd ~ && rm -rf ~/labs/js-deob

This removes every file this lab created. Nothing else on the system was changed.

Lab complete. You read, beautified and resolved obfuscated JavaScript without ever trusting it to run itself. Next, Cross-Site Scripting (XSS) applies the same "read before you run" habit to a live payload in a browser.

Sign in to track progress and send feedback.

Related