[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HDZGSWZ5GT9MYF8HD7BBEF":3,"skill-same:01M6HDZGSWZ5GT9MYF8HD7BBEF":99},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":60,"commitSha":61,"skillDirectory":62,"forksCount":63,"repositoryHtmlUrl":64,"repositoryHomepageUrl":6,"ownerHtmlUrl":65,"ownerBlogUrl":6,"ownerDescription":66,"updatedAt":67,"install":68,"resources":81},"01M6HDZGSWZ5GT9MYF8HD7BBEF","deobfuscating-javascript-malware",null,"Deobfuscates malicious JavaScript code used in web-based attacks, phishing pages, and dropper scripts by reversing encoding layers, eval chains, string manipulation, and control flow obfuscation to reveal the original malicious logic. Activates...","HenriqueMC17\u002Fagente-core","HenriqueMC17","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F206460478?v=4","01M6HB63HBBF18AC4H09XTB549","Henrique Monteiro Cardoso","01M6HB63NGSQXWKWCFWW2B20W0",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fdeobfuscating-javascript-malware\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"javascript","malware","deobfuscating javascript malware","t1059","layers","attacks","id","pages","control","007","cm","eval","analysis","malicious","script-analysis","web-malware","deobfuscation","phishing","code","cybersecurity","2026-11-10 10:12:30",false,"---\nname: deobfuscating-javascript-malware\ndescription: Deobfuscates malicious JavaScript code used in web-based attacks, phishing pages, and dropper scripts by reversing encoding layers, eval chains, string manipulation, and control flow obfuscation to reveal the original malicious logic. Activates...\ndomain: cybersecurity\nsubdomain: malware-analysis\ntags:\n- malware\n- JavaScript\n- deobfuscation\n- web-malware\n- script-analysis\nversion: 1.0.0\nauthor: mahipal\nlicense: Apache-2.0\nnist_csf:\n- DE.AE-02\n- RS.AN-03\n- ID.RA-01\n- DE.CM-01\nmitre_attack:\n- T1027\n- T1027.010\n- T1140\n- T1059.007\n- T1027.006\ncategory: deobfuscating-javascript-malware\n---\n# Deobfuscating-Javascript-Malware\n\n## Overview\nDeobfuscates malicious JavaScript code used in web-based attacks, phishing pages, and dropper scripts by reversing encoding layers, eval chains, string manipulation, and control flow obfuscation to reveal the original malicious logic. Activates for requests involving JavaScript malware analysis, script deobfuscation, web skimmer analysis, or obfuscated dropper investigation.\n\n\n\n# Deobfuscating JavaScript Malware\n\n## When to Use\n\n- Investigating a phishing page with obfuscated JavaScript that performs credential harvesting or redirect\n- Analyzing a web skimmer (Magecart-style) injected into an e-commerce site\n- Deobfuscating a JavaScript dropper that downloads and executes second-stage malware\n- Examining malicious email attachments containing HTML files with embedded obfuscated scripts\n- Analyzing browser exploit kits that use heavy JavaScript obfuscation to hide exploit delivery\n\n**Do not use** for obfuscated JavaScript that is merely minified production code; use a standard beautifier instead.\n\n## Prerequisites\n\n- Node.js 18+ installed for executing and debugging JavaScript in a controlled environment\n- Python 3.8+ with `jsbeautifier` library for code formatting\n- Browser developer tools (Chrome DevTools) for controlled execution in an isolated browser\n- CyberChef (https:\u002F\u002Fgchq.github.io\u002FCyberChef\u002F) for encoding\u002Fdecoding operations\n- de4js or JStillery for automated JavaScript deobfuscation\n- Isolated analysis VM with no access to production systems or sensitive data\n\n## Workflow\n\n### Step 1: Safely Extract and Examine the Obfuscated Script\n\nIsolate the malicious JavaScript without executing it:\n\n```bash\n# Extract JavaScript from HTML file\npython3 \u003C\u003C 'PYEOF'\nfrom html.parser import HTMLParser\n\nclass ScriptExtractor(HTMLParser):\n    def __init__(self):\n        super().__init__()\n        self.in_script = False\n        self.scripts = []\n        self.current = \"\"\n\n    def handle_starttag(self, tag, attrs):\n        if tag == \"script\":\n            self.in_script = True\n            self.current = \"\"\n\n    def handle_endtag(self, tag):\n        if tag == \"script\":\n            self.in_script = False\n            if self.current.strip():\n                self.scripts.append(self.current)\n\n    def handle_data(self, data):\n        if self.in_script:\n            self.current += data\n\nwith open(\"malicious_page.html\") as f:\n    parser = ScriptExtractor()\n    parser.feed(f.read())\n\nfor i, script in enumerate(parser.scripts):\n    with open(f\"script_{i}.js\", \"w\") as f:\n        f.write(script)\n    print(f\"Extracted script_{i}.js ({len(script)} bytes)\")\nPYEOF\n\n# Beautify the extracted JavaScript\nnpx js-beautify script_0.js -o script_0_pretty.js\n```\n\n### Step 2: Identify Obfuscation Techniques\n\nCategorize the obfuscation methods used:\n\n```\nCommon JavaScript Obfuscation Techniques:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nString Encoding:\n  - Hex encoding:          \"\\x68\\x65\\x6c\\x6c\\x6f\" -> \"hello\"\n  - Unicode escapes:       \"\\u0068\\u0065\\u006c\\u006c\\u006f\" -> \"hello\"\n  - Base64:                atob(\"aGVsbG8=\") -> \"hello\"\n  - charCodeAt\u002FfromCharCode: String.fromCharCode(104,101,108,108,111)\n  - Array-based lookup:    var _0x1234 = [\"hello\",\"world\"]; _0x1234[0]\n\nEval Chains:\n  - eval(atob(\"...\"))\n  - eval(unescape(\"...\"))\n  - new Function(\"return \" + decoded)()\n  - document.write(\"\u003Cscript>\" + decoded + \"\u003C\u002Fscript>\")\n  - setTimeout(decoded, 0)\n\nControl Flow:\n  - Switch-case dispatcher with shuffled case order\n  - Opaque predicates (always-true\u002Ffalse conditions)\n  - Dead code insertion\n  - Variable name mangling (_0x4a3b, _0xab12)\n\nAnti-Analysis:\n  - Debugger traps: setInterval(function(){debugger;}, 100)\n  - Console detection: overriding console.log\n  - Timing checks: performance.now() deltas\n  - DevTools detection: window.outerWidth - window.innerWidth > 100\n```\n\n### Step 3: Remove Anti-Analysis Protections\n\nNeutralize anti-debugging and anti-analysis traps:\n\n```javascript\n\u002F\u002F Remove debugger traps before analysis\n\u002F\u002F Replace in the obfuscated script:\n\n\u002F\u002F Before:\nsetInterval(function() { debugger; }, 100);\n\n\u002F\u002F After (neutralized):\nsetInterval(function() { \u002F* debugger removed *\u002F }, 100);\n\n\u002F\u002F Neutralize DevTools detection\n\u002F\u002F Before:\nif (window.outerWidth - window.innerWidth > 160) { window.location = \"about:blank\"; }\n\n\u002F\u002F After:\nif (false) { window.location = \"about:blank\"; }\n\n\u002F\u002F Neutralize timing checks\n\u002F\u002F Override performance.now to return consistent values\nconst originalNow = performance.now;\nperformance.now = function() { return 0; };\n```\n\n### Step 4: Decode String Obfuscation Layers\n\nProgressively decode encoded strings:\n\n```python\n# Python script to decode common JS obfuscation patterns\nimport re\nimport base64\nimport urllib.parse\n\ndef decode_hex_strings(code):\n    \"\"\"Replace \\\\xNN sequences with ASCII characters\"\"\"\n    def hex_replace(match):\n        hex_str = match.group(0)\n        try:\n            return bytes.fromhex(hex_str.replace(\"\\\\x\", \"\")).decode(\"ascii\")\n        except:\n            return hex_str\n    return re.sub(r'(?:\\\\x[0-9a-fA-F]{2})+', hex_replace, code)\n\ndef decode_unicode_escapes(code):\n    \"\"\"Replace \\\\uNNNN sequences with characters\"\"\"\n    def unicode_replace(match):\n        return chr(int(match.group(1), 16))\n    return re.sub(r'\\\\u([0-9a-fA-F]{4})', unicode_replace, code)\n\ndef decode_charcode_arrays(code):\n    \"\"\"Resolve String.fromCharCode calls\"\"\"\n    def charcode_replace(match):\n        codes = [int(c.strip()) for c in match.group(1).split(\",\")]\n        return '\"' + \"\".join(chr(c) for c in codes) + '\"'\n    return re.sub(r'String\\.fromCharCode\\(([0-9,\\s]+)\\)', charcode_replace, code)\n\ndef decode_base64_strings(code):\n    \"\"\"Resolve atob() calls with static strings\"\"\"\n    def atob_replace(match):\n        try:\n            decoded = base64.b64decode(match.group(1)).decode(\"utf-8\")\n            return f'\"{decoded}\"'\n        except:\n            return match.group(0)\n    return re.sub(r'atob\\([\"\\']([A-Za-z0-9+\u002F=]+)[\"\\']\\)', atob_replace, code)\n\n# Apply all decoders\nwith open(\"script_0.js\") as f:\n    code = f.read()\n\ncode = decode_hex_strings(code)\ncode = decode_unicode_escapes(code)\ncode = decode_charcode_arrays(code)\ncode = decode_base64_strings(code)\n\nwith open(\"script_0_decoded.js\", \"w\") as f:\n    f.write(code)\nprint(\"Decoded strings written to script_0_decoded.js\")\n```\n\n### Step 5: Resolve Eval Chains Safely\n\nUnwrap eval\u002FFunction constructor chains without executing:\n\n```javascript\n\u002F\u002F Node.js script to safely resolve eval chains\n\u002F\u002F Run in isolated environment: node --experimental-vm-modules deobfuscate.js\n\nconst vm = require('vm');\n\n\u002F\u002F Create sandboxed context with logging\nconst sandbox = {\n    eval: function(code) {\n        console.log(\"=== EVAL INTERCEPTED ===\");\n        console.log(code.substring(0, 500));\n        console.log(\"========================\");\n        return code; \u002F\u002F Return the code instead of executing it\n    },\n    document: {\n        write: function(html) {\n            console.log(\"=== DOCUMENT.WRITE INTERCEPTED ===\");\n            console.log(html.substring(0, 500));\n        },\n        getElementById: function() { return { innerHTML: \"\" }; }\n    },\n    window: { location: { href: \"\" } },\n    atob: function(s) { return Buffer.from(s, 'base64').toString(); },\n    unescape: unescape,\n    setTimeout: function(fn) { if (typeof fn === 'string') console.log(\"TIMEOUT CODE:\", fn); },\n    console: console,\n    String: String,\n    Array: Array,\n    parseInt: parseInt,\n    RegExp: RegExp,\n};\n\nconst context = vm.createContext(sandbox);\n\n\u002F\u002F Load and execute the obfuscated script in sandbox\nconst fs = require('fs');\nconst code = fs.readFileSync('script_0.js', 'utf8');\n\ntry {\n    vm.runInContext(code, context, { timeout: 5000 });\n} catch(e) {\n    console.log(\"Execution error (expected):\", e.message);\n}\n```\n\n### Step 6: Analyze the Deobfuscated Payload\n\nExamine the revealed malicious logic:\n\n```\nDeobfuscated Malware Categories and IOC Extraction:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nCredential Harvester:\n  - Form action URLs (exfiltration endpoints)\n  - XMLHttpRequest\u002Ffetch destinations\n  - Targeted input field names (username, password, cc_number)\n\nWeb Skimmer (Magecart):\n  - Payment form overlay injection\n  - Card data exfiltration URLs\n  - Keylogger event listeners (onkeypress, oninput)\n\nRedirect Script:\n  - Destination URLs in location.href assignments\n  - Conditional redirects based on user-agent or referrer\n  - Cloaking logic (show benign content to bots)\n\nExploit Kit Landing:\n  - Browser\u002Fplugin version checks\n  - Exploit payload URLs\n  - Shellcode embedded as arrays or encoded strings\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Eval Chain** | Nested layers of eval(), Function(), or document.write() calls that each decode one layer of obfuscation before passing to the next |\n| **String Array Rotation** | Obfuscation technique storing all strings in a shuffled array and accessing them by computed index to hide string literals |\n| **Dead Code Insertion** | Adding non-functional code blocks that never execute to increase analysis complexity and confuse pattern matching |\n| **Opaque Predicate** | Conditional expression whose outcome is predetermined but difficult to determine statically; used to obscure control flow |\n| **Anti-Debugging** | JavaScript techniques to detect and thwart browser DevTools or debugger usage including debugger statements and timing checks |\n| **Web Skimmer** | Malicious JavaScript injected into e-commerce sites to steal payment card data from checkout forms (Magecart attack) |\n\n## Tools & Systems\n\n- **CyberChef**: GCHQ's web-based tool for encoding\u002Fdecoding transformations useful for unwinding multi-layer obfuscation\n- **de4js**: Online JavaScript deobfuscator supporting common obfuscation tools (obfuscator.io, JScrambler)\n- **Node.js VM Module**: Sandboxed JavaScript execution environment for safely evaluating obfuscated code with intercepted APIs\n- **Chrome DevTools**: Browser developer tools for stepping through JavaScript execution with breakpoints and console access\n- **JSDetox**: JavaScript malware analysis tool providing execution emulation and deobfuscation\n\n## Common Scenarios\n\n### Scenario: Deobfuscating a Magecart Web Skimmer\n\n**Context**: A compromised e-commerce site has obfuscated JavaScript injected into its checkout page. The script needs deobfuscation to identify the data exfiltration endpoint and determine what customer data was stolen.\n\n**Approach**:\n1. Extract the injected script from the page source (often appended to a legitimate JS file or loaded from an external domain)\n2. Beautify the code and identify the obfuscation technique (typically string array + rotation + hex encoding)\n3. Decode string encoding layers (hex -> Unicode -> base64) using the Python decoder script\n4. Resolve the string array by evaluating the array definition and rotation function\n5. Identify the form targeting logic (querySelector for payment form fields)\n6. Extract the exfiltration URL from the XMLHttpRequest or fetch call\n7. Document stolen data fields and exfiltration endpoint for incident response\n\n**Pitfalls**:\n- Executing obfuscated scripts on a connected system (the script may phone home during analysis)\n- Not removing anti-debugging traps before using browser DevTools (infinite debugger loops)\n- Missing additional obfuscation layers loaded dynamically from external URLs\n- Overlooking base64-encoded inline images or data URIs that may contain additional scripts\n\n## Output Format\n\n```\nJAVASCRIPT MALWARE DEOBFUSCATION REPORT\n=========================================\nSource:           checkout.js (injected into example-shop.com)\nObfuscation:      obfuscator.io (string array + rotation + hex encoding)\nLayers Removed:   3\n\nOBFUSCATION TECHNIQUES IDENTIFIED\n[1] String array with 247 entries, rotated by 0x1a3\n[2] Hex-encoded string references (\\x68\\x65\\x6c\\x6c\\x6f)\n[3] Base64-wrapped eval chain (2 layers)\n[4] Anti-debugging: setInterval debugger trap\n\nDEOBFUSCATED FUNCTIONALITY\nType:             Magecart Payment Card Skimmer\nTarget Forms:     input[name*=\"card\"], input[name*=\"cc_\"]\nData Captured:    Card number, expiration, CVV, cardholder name\nExfil Method:     POST via XMLHttpRequest\nExfil URL:        hxxps:\u002F\u002Fanalytics-cdn[.]com\u002Fcollect\nExfil Format:     JSON { \"cn\": card_number, \"exp\": expiry, \"cv\": cvv }\nTrigger:          Form submit event on checkout page\n\nEXTRACTED IOCs\nDomains:          analytics-cdn[.]com\nIPs:              185.220.101[.]42\nURLs:             hxxps:\u002F\u002Fanalytics-cdn[.]com\u002Fcollect\n                  hxxps:\u002F\u002Fanalytics-cdn[.]com\u002Fgate.js\n```\n","# Deobfuscating-Javascript-Malware\n\n## Overview\nDeobfuscates malicious JavaScript code used in web-based attacks, phishing pages, and dropper scripts by reversing encoding layers, eval chains, string manipulation, and control flow obfuscation to reveal the original malicious logic. Activates for requests involving JavaScript malware analysis, script deobfuscation, web skimmer analysis, or obfuscated dropper investigation.\n\n\n\n# Deobfuscating JavaScript Malware\n\n## When to Use\n\n- Investigating a phishing page with obfuscated JavaScript that performs credential harvesting or redirect\n- Analyzing a web skimmer (Magecart-style) injected into an e-commerce site\n- Deobfuscating a JavaScript dropper that downloads and executes second-stage malware\n- Examining malicious email attachments containing HTML files with embedded obfuscated scripts\n- Analyzing browser exploit kits that use heavy JavaScript obfuscation to hide exploit delivery\n\n**Do not use** for obfuscated JavaScript that is merely minified production code; use a standard beautifier instead.\n\n## Prerequisites\n\n- Node.js 18+ installed for executing and debugging JavaScript in a controlled environment\n- Python 3.8+ with `jsbeautifier` library for code formatting\n- Browser developer tools (Chrome DevTools) for controlled execution in an isolated browser\n- CyberChef (https:\u002F\u002Fgchq.github.io\u002FCyberChef\u002F) for encoding\u002Fdecoding operations\n- de4js or JStillery for automated JavaScript deobfuscation\n- Isolated analysis VM with no access to production systems or sensitive data\n\n## Workflow\n\n### Step 1: Safely Extract and Examine the Obfuscated Script\n\nIsolate the malicious JavaScript without executing it:\n\n```bash\n# Extract JavaScript from HTML file\npython3 \u003C\u003C 'PYEOF'\nfrom html.parser import HTMLParser\n\nclass ScriptExtractor(HTMLParser):\n    def __init__(self):\n        super().__init__()\n        self.in_script = False\n        self.scripts = []\n        self.current = \"\"\n\n    def handle_starttag(self, tag, attrs):\n        if tag == \"script\":\n            self.in_script = True\n            self.current = \"\"\n\n    def handle_endtag(self, tag):\n        if tag == \"script\":\n            self.in_script = False\n            if self.current.strip():\n                self.scripts.append(self.current)\n\n    def handle_data(self, data):\n        if self.in_script:\n            self.current += data\n\nwith open(\"malicious_page.html\") as f:\n    parser = ScriptExtractor()\n    parser.feed(f.read())\n\nfor i, script in enumerate(parser.scripts):\n    with open(f\"script_{i}.js\", \"w\") as f:\n        f.write(script)\n    print(f\"Extracted script_{i}.js ({len(script)} bytes)\")\nPYEOF\n\n# Beautify the extracted JavaScript\nnpx js-beautify script_0.js -o script_0_pretty.js\n```\n\n### Step 2: Identify Obfuscation Techniques\n\nCategorize the obfuscation methods used:\n\n```\nCommon JavaScript Obfuscation Techniques:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nString Encoding:\n  - Hex encoding:          \"\\x68\\x65\\x6c\\x6c\\x6f\" -> \"hello\"\n  - Unicode escapes:       \"\\u0068\\u0065\\u006c\\u006c\\u006f\" -> \"hello\"\n  - Base64:                atob(\"aGVsbG8=\") -> \"hello\"\n  - charCodeAt\u002FfromCharCode: String.fromCharCode(104,101,108,108,111)\n  - Array-based lookup:    var _0x1234 = [\"hello\",\"world\"]; _0x1234[0]\n\nEval Chains:\n  - eval(atob(\"...\"))\n  - eval(unescape(\"...\"))\n  - new Function(\"return \" + decoded)()\n  - document.write(\"\u003Cscript>\" + decoded + \"\u003C\u002Fscript>\")\n  - setTimeout(decoded, 0)\n\nControl Flow:\n  - Switch-case dispatcher with shuffled case order\n  - Opaque predicates (always-true\u002Ffalse conditions)\n  - Dead code insertion\n  - Variable name mangling (_0x4a3b, _0xab12)\n\nAnti-Analysis:\n  - Debugger traps: setInterval(function(){debugger;}, 100)\n  - Console detection: overriding console.log\n  - Timing checks: performance.now() deltas\n  - DevTools detection: window.outerWidth - window.innerWidth > 100\n```\n\n### Step 3: Remove Anti-Analysis Protections\n\nNeutralize anti-debugging and anti-analysis traps:\n\n```javascript\n\u002F\u002F Remove debugger traps before analysis\n\u002F\u002F Replace in the obfuscated script:\n\n\u002F\u002F Before:\nsetInterval(function() { debugger; }, 100);\n\n\u002F\u002F After (neutralized):\nsetInterval(function() { \u002F* debugger removed *\u002F }, 100);\n\n\u002F\u002F Neutralize DevTools detection\n\u002F\u002F Before:\nif (window.outerWidth - window.innerWidth > 160) { window.location = \"about:blank\"; }\n\n\u002F\u002F After:\nif (false) { window.location = \"about:blank\"; }\n\n\u002F\u002F Neutralize timing checks\n\u002F\u002F Override performance.now to return consistent values\nconst originalNow = performance.now;\nperformance.now = function() { return 0; };\n```\n\n### Step 4: Decode String Obfuscation Layers\n\nProgressively decode encoded strings:\n\n```python\n# Python script to decode common JS obfuscation patterns\nimport re\nimport base64\nimport urllib.parse\n\ndef decode_hex_strings(code):\n    \"\"\"Replace \\\\xNN sequences with ASCII characters\"\"\"\n    def hex_replace(match):\n        hex_str = match.group(0)\n        try:\n            return bytes.fromhex(hex_str.replace(\"\\\\x\", \"\")).decode(\"ascii\")\n        except:\n            return hex_str\n    return re.sub(r'(?:\\\\x[0-9a-fA-F]{2})+', hex_replace, code)\n\ndef decode_unicode_escapes(code):\n    \"\"\"Replace \\\\uNNNN sequences with characters\"\"\"\n    def unicode_replace(match):\n        return chr(int(match.group(1), 16))\n    return re.sub(r'\\\\u([0-9a-fA-F]{4})', unicode_replace, code)\n\ndef decode_charcode_arrays(code):\n    \"\"\"Resolve String.fromCharCode calls\"\"\"\n    def charcode_replace(match):\n        codes = [int(c.strip()) for c in match.group(1).split(\",\")]\n        return '\"' + \"\".join(chr(c) for c in codes) + '\"'\n    return re.sub(r'String\\.fromCharCode\\(([0-9,\\s]+)\\)', charcode_replace, code)\n\ndef decode_base64_strings(code):\n    \"\"\"Resolve atob() calls with static strings\"\"\"\n    def atob_replace(match):\n        try:\n            decoded = base64.b64decode(match.group(1)).decode(\"utf-8\")\n            return f'\"{decoded}\"'\n        except:\n            return match.group(0)\n    return re.sub(r'atob\\([\"\\']([A-Za-z0-9+\u002F=]+)[\"\\']\\)', atob_replace, code)\n\n# Apply all decoders\nwith open(\"script_0.js\") as f:\n    code = f.read()\n\ncode = decode_hex_strings(code)\ncode = decode_unicode_escapes(code)\ncode = decode_charcode_arrays(code)\ncode = decode_base64_strings(code)\n\nwith open(\"script_0_decoded.js\", \"w\") as f:\n    f.write(code)\nprint(\"Decoded strings written to script_0_decoded.js\")\n```\n\n### Step 5: Resolve Eval Chains Safely\n\nUnwrap eval\u002FFunction constructor chains without executing:\n\n```javascript\n\u002F\u002F Node.js script to safely resolve eval chains\n\u002F\u002F Run in isolated environment: node --experimental-vm-modules deobfuscate.js\n\nconst vm = require('vm');\n\n\u002F\u002F Create sandboxed context with logging\nconst sandbox = {\n    eval: function(code) {\n        console.log(\"=== EVAL INTERCEPTED ===\");\n        console.log(code.substring(0, 500));\n        console.log(\"========================\");\n        return code; \u002F\u002F Return the code instead of executing it\n    },\n    document: {\n        write: function(html) {\n            console.log(\"=== DOCUMENT.WRITE INTERCEPTED ===\");\n            console.log(html.substring(0, 500));\n        },\n        getElementById: function() { return { innerHTML: \"\" }; }\n    },\n    window: { location: { href: \"\" } },\n    atob: function(s) { return Buffer.from(s, 'base64').toString(); },\n    unescape: unescape,\n    setTimeout: function(fn) { if (typeof fn === 'string') console.log(\"TIMEOUT CODE:\", fn); },\n    console: console,\n    String: String,\n    Array: Array,\n    parseInt: parseInt,\n    RegExp: RegExp,\n};\n\nconst context = vm.createContext(sandbox);\n\n\u002F\u002F Load and execute the obfuscated script in sandbox\nconst fs = require('fs');\nconst code = fs.readFileSync('script_0.js', 'utf8');\n\ntry {\n    vm.runInContext(code, context, { timeout: 5000 });\n} catch(e) {\n    console.log(\"Execution error (expected):\", e.message);\n}\n```\n\n### Step 6: Analyze the Deobfuscated Payload\n\nExamine the revealed malicious logic:\n\n```\nDeobfuscated Malware Categories and IOC Extraction:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nCredential Harvester:\n  - Form action URLs (exfiltration endpoints)\n  - XMLHttpRequest\u002Ffetch destinations\n  - Targeted input field names (username, password, cc_number)\n\nWeb Skimmer (Magecart):\n  - Payment form overlay injection\n  - Card data exfiltration URLs\n  - Keylogger event listeners (onkeypress, oninput)\n\nRedirect Script:\n  - Destination URLs in location.href assignments\n  - Conditional redirects based on user-agent or referrer\n  - Cloaking logic (show benign content to bots)\n\nExploit Kit Landing:\n  - Browser\u002Fplugin version checks\n  - Exploit payload URLs\n  - Shellcode embedded as arrays or encoded strings\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Eval Chain** | Nested layers of eval(), Function(), or document.write() calls that each decode one layer of obfuscation before passing to the next |\n| **String Array Rotation** | Obfuscation technique storing all strings in a shuffled array and accessing them by computed index to hide string literals |\n| **Dead Code Insertion** | Adding non-functional code blocks that never execute to increase analysis complexity and confuse pattern matching |\n| **Opaque Predicate** | Conditional expression whose outcome is predetermined but difficult to determine statically; used to obscure control flow |\n| **Anti-Debugging** | JavaScript techniques to detect and thwart browser DevTools or debugger usage including debugger statements and timing checks |\n| **Web Skimmer** | Malicious JavaScript injected into e-commerce sites to steal payment card data from checkout forms (Magecart attack) |\n\n## Tools & Systems\n\n- **CyberChef**: GCHQ's web-based tool for encoding\u002Fdecoding transformations useful for unwinding multi-layer obfuscation\n- **de4js**: Online JavaScript deobfuscator supporting common obfuscation tools (obfuscator.io, JScrambler)\n- **Node.js VM Module**: Sandboxed JavaScript execution environment for safely evaluating obfuscated code with intercepted APIs\n- **Chrome DevTools**: Browser developer tools for stepping through JavaScript execution with breakpoints and console access\n- **JSDetox**: JavaScript malware analysis tool providing execution emulation and deobfuscation\n\n## Common Scenarios\n\n### Scenario: Deobfuscating a Magecart Web Skimmer\n\n**Context**: A compromised e-commerce site has obfuscated JavaScript injected into its checkout page. The script needs deobfuscation to identify the data exfiltration endpoint and determine what customer data was stolen.\n\n**Approach**:\n1. Extract the injected script from the page source (often appended to a legitimate JS file or loaded from an external domain)\n2. Beautify the code and identify the obfuscation technique (typically string array + rotation + hex encoding)\n3. Decode string encoding layers (hex -> Unicode -> base64) using the Python decoder script\n4. Resolve the string array by evaluating the array definition and rotation function\n5. Identify the form targeting logic (querySelector for payment form fields)\n6. Extract the exfiltration URL from the XMLHttpRequest or fetch call\n7. Document stolen data fields and exfiltration endpoint for incident response\n\n**Pitfalls**:\n- Executing obfuscated scripts on a connected system (the script may phone home during analysis)\n- Not removing anti-debugging traps before using browser DevTools (infinite debugger loops)\n- Missing additional obfuscation layers loaded dynamically from external URLs\n- Overlooking base64-encoded inline images or data URIs that may contain additional scripts\n\n## Output Format\n\n```\nJAVASCRIPT MALWARE DEOBFUSCATION REPORT\n=========================================\nSource:           checkout.js (injected into example-shop.com)\nObfuscation:      obfuscator.io (string array + rotation + hex encoding)\nLayers Removed:   3\n\nOBFUSCATION TECHNIQUES IDENTIFIED\n[1] String array with 247 entries, rotated by 0x1a3\n[2] Hex-encoded string references (\\x68\\x65\\x6c\\x6c\\x6f)\n[3] Base64-wrapped eval chain (2 layers)\n[4] Anti-debugging: setInterval debugger trap\n\nDEOBFUSCATED FUNCTIONALITY\nType:             Magecart Payment Card Skimmer\nTarget Forms:     input[name*=\"card\"], input[name*=\"cc_\"]\nData Captured:    Card number, expiration, CVV, cardholder name\nExfil Method:     POST via XMLHttpRequest\nExfil URL:        hxxps:\u002F\u002Fanalytics-cdn[.]com\u002Fcollect\nExfil Format:     JSON { \"cn\": card_number, \"exp\": expiry, \"cv\": cvv }\nTrigger:          Form submit event on checkout page\n\nEXTRACTED IOCs\nDomains:          analytics-cdn[.]com\nIPs:              185.220.101[.]42\nURLs:             hxxps:\u002F\u002Fanalytics-cdn[.]com\u002Fcollect\n                  hxxps:\u002F\u002Fanalytics-cdn[.]com\u002Fgate.js\n```\n",{"name":5,"tags":44,"author":46,"domain":38,"license":15,"version":47,"category":5,"nist_csf":48,"subdomain":53,"description":7,"mitre_attack":54},[20,45,35,34,33],"JavaScript","mahipal","1.0.0",[49,50,51,52],"DE.AE-02","RS.AN-03","ID.RA-01","DE.CM-01","malware-analysis",[55,56,57,58,59],"T1027","T1027.010","T1140","T1059.007","T1027.006","main","5eea5b3296f4673b5f481e8bcc1ba76281149f16","modules\u002Fdeobfuscating-javascript-malware",0,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core","https:\u002F\u002Fgithub.com\u002FHenriqueMC17","Qualquer tecnologia suficientemente avançada é indistinguível da mágica.","2026-09-28 22:40:38",{"source":8,"skillName":5,"commands":69,"prompt":79,"zipAvailable":80},[70,73,76],{"tool":71,"command":72},"npx","npx skills add HenriqueMC17\u002Fagente-core --skill deobfuscating-javascript-malware",{"tool":74,"command":75},"bunx","bunx skills add HenriqueMC17\u002Fagente-core --skill deobfuscating-javascript-malware",{"tool":77,"command":78},"pnpm","pnpm dlx skills add HenriqueMC17\u002Fagente-core --skill deobfuscating-javascript-malware","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fdeobfuscating-javascript-malware\u002FSKILL.md",true,[82,87,93],{"path":83,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":85,"sourceHtmlUrl":86},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fdeobfuscating-javascript-malware\u002FLICENSE",{"path":88,"resourceType":89,"resourceTypeDesc":90,"sizeBytes":91,"sourceHtmlUrl":92},"references\u002Fapi-reference.md","REFERENCE","参考文档",2029,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fdeobfuscating-javascript-malware\u002Freferences\u002Fapi-reference.md",{"path":94,"resourceType":95,"resourceTypeDesc":96,"sizeBytes":97,"sourceHtmlUrl":98},"scripts\u002Fagent.py","SCRIPT","脚本",7239,"https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fdeobfuscating-javascript-malware\u002Fscripts\u002Fagent.py",[100,131,157,179,195,215],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":111,"publishedAt":39},"01M6HPFF0RCN0X6WT5EBSV71GY","validating-backup-integrity-for-recovery","Validate backup integrity through cryptographic hash verification, automated restore testing, corruption detection, and recoverability checks to ensure backups are reliable for disaster recovery and ransomware response scenarios.","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Fvalidating-backup-integrity-for-recovery\u002FSKILL.md",[106],{"categoryNo":107,"categoryName":108,"taxonomyType":109,"taxonomyTypeDesc":110},"01JBSEEDCAT000000000000008","测试与质量","SCENARIO","使用场景",[112,113,114,115,116,117,38,118,119,120,121,122,123,124,125,126,127,128,129,130],"integrity","backup","recovery","validating backup integrity for recovery","for","testing","validate","verification","hash-verification","incident-response","ransomware","detection","t1078","t1490","disaster-recovery","restore","incident","disaster recovery","ransomware response",{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":137,"publishedAt":39},"01M6HPFAWJVFK25Q33K3T7WQ8G","triaging-vulnerabilities-with-ssvc-framework","Triage and prioritize vulnerabilities using CISA's Stakeholder-Specific Vulnerability Categorization (SSVC) decision tree framework to produce actionable remediation priorities.","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftriaging-vulnerabilities-with-ssvc-framework\u002FSKILL.md",[],[138,139,140,141,142,38,143,144,145,146,147,148,149,150,151,152,153,154,155,156],"vulnerabilities","framework","ssvc","triaging vulnerabilities with ssvc framework","with","triage and prioritize","CISA","vulnerability-management","risk-management","cvss","remediation","vulnerability","prioritization","decision-tree","prioritize","decision","priorities","actionable","tree",{"skillNo":158,"name":159,"nameZh":6,"description":160,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":161,"categories":162,"keywords":163,"publishedAt":39},"01M6HPF6JS9X72WP59094H3ASQ","triaging-security-incident","Performs initial triage of security incidents to determine severity, scope, and required response actions using the NIST SP 800-61r3 and SANS PICERL frameworks. Classifies incidents by type, assigns priority based on business impact, and routes...","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftriaging-security-incident\u002FSKILL.md",[],[164,165,128,38,166,167,168,124,125,31,169,170,171,172,173,174,175,176,177,178],"security","triaging security incident","actions","soc","NIST","severity-classification","incident-triage","SANS-PICERL","SOC-operations","picerl","conversion","isolation","scope","impact","consistency",{"skillNo":180,"name":181,"nameZh":6,"description":182,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":183,"categories":184,"keywords":185,"publishedAt":39},"01M6HPF2EX6ZYNYYHKBRJN7GEF","triaging-security-incident-with-ir-playbook","Classify and prioritize security incidents using structured IR playbooks to determine severity, assign response teams, and initiate appropriate response procedures.","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftriaging-security-incident-with-ir-playbook\u002FSKILL.md",[],[164,186,187,165,128,142,38,188,167,121,189,190,124,125,191,169,152,192,193,194],"playbook","triaging security incident with ir playbook","teams","IR-playbook","severity","classification","classify","incidents","initiate",{"skillNo":196,"name":197,"nameZh":6,"description":198,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":199,"categories":200,"keywords":201,"publishedAt":39},"01M6HPEY9XPGE7X95AG4XJFQAW","triaging-security-alerts-in-splunk","Triages security alerts in Splunk Enterprise Security by classifying severity, investigating notable events, correlating related telemetry, and making escalation or closure decisions using SPL queries and the Incident Review dashboard. Use when...","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftriaging-security-alerts-in-splunk\u002FSKILL.md",[],[164,202,203,204,205,206,38,207,208,209,167,210,124,211,212,213,172,29,128,214],"security alerts","splunk","triaging security alerts in splunk","alerts","review","siem","dashboard","search","correlation-search","t1566","notable-events","incident-review","de",{"skillNo":216,"name":217,"nameZh":6,"description":218,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":219,"categories":220,"keywords":221,"publishedAt":39},"01M6HPET6XGEPEJPN7V032JGZ0","tracking-threat-actor-infrastructure","Threat actor infrastructure tracking involves monitoring and mapping adversary-controlled assets including command-and-control (C2) servers, phishing domains, exploit kit hosts, bulletproof hosting, a","https:\u002F\u002Fgithub.com\u002FHenriqueMC17\u002Fagente-core\u002Fblob\u002Fmain\u002Fmodules\u002Ftracking-threat-actor-infrastructure\u002FSKILL.md",[],[222,223,224,225,38,226,227,228,229,230,231,211,232,233,29,234,214,235,236,237],"infrastructure","tracking threat actor infrastructure","tracking","threat","monitoring","mitre-attack","threat-actor","threat-intelligence","command-and-control","dns","command","exploit","intelligence","domains","kit","hosts"]