Join our Newsletter — 33% off our NHI Course
Home› Guides› Deobfuscating Malicious JavaScript and PowerShell: Safe Analysis for…
Guide Attack Techniques & Malware

Deobfuscating Malicious JavaScript and PowerShell: Safe Analysis for Defenders

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 13 min read
On this page

An obfuscated script lands in the triage queue, and the analyst has to work out what it does without letting it run on anything that matters. JavaScript droppers delivered by email or download and layered PowerShell stagers are among the most common first stages in commodity and targeted intrusions, and almost all of them are obfuscated. This guide is a learning module for malware analysts and SOC tier 2 staff: how to build a safe lab, how to recognise the common obfuscation patterns in each language, how to peel layers statically before anything executes, and how Script Block Logging and AMSI give you the decoded code for free when a script has already run. It is defensive only and contains no working samples or payloads.

Key takeaways

  • Static before dynamic. Decode, beautify and resolve strings in a text tool first; only execute or emulate inside an isolated, disposable lab when static work stalls.
  • Every layer ends in an execution sink. Obfuscated JavaScript funnels into eval, Function or a WScript call; PowerShell funnels into Invoke-Expression, a script block or a child process. Find the sink and print instead of run.
  • The host has often decoded it already. PowerShell event 4104 records the script blocks it processes, and AMSI receives content once it is plain, so check the endpoint telemetry before you start peeling.
  • Never run a sample in a general interpreter on a workstation. Node.js and PowerShell run code with the full rights of the user; emulators and instrumented sandboxes exist so you do not have to.
  • Deobfuscation is for intelligence, not curiosity. The goal is indicators (URLs, hashes, file paths, persistence), behaviour, and detection gaps, recorded so the next sample is faster.

Why attackers obfuscate

MITRE ATT&CK tracks this as T1027 Obfuscated Files or Information, with sub-technique T1027.010 Command Obfuscation for scripts and command lines, while the runtime unpacking is T1140 Deobfuscate/Decode Files or Information. The execution itself is T1059.001 PowerShell or T1059.007 JavaScript, usually after T1204.002 Malicious File or T1566.001 Spearphishing Attachment. The technique pages are covered in the T1027 Obfuscated Files or Information Defensive Guide and MITRE ATT&CK T1140 Deobfuscate/Decode Files or Information; this page is about the analyst's hands-on work.

Microsoft's AMSI documentation describes the arms race plainly: authors first split strings to break signatures, then moved to Base64, then to simple XOR schemes beyond what engines emulate, and finally to trivial obfuscation that looks benign enough that a signature would cause unacceptable false positives. Obfuscation buys three things: it defeats static signatures, slows down human triage, and hides the indicators (download URLs, second-stage names) defenders would block. It does not change behaviour, which is why behaviour-based analysis and host telemetry win in the end.

Safe analysis environment

Treat every sample as live. The lab is there to make a mistake survivable.

OptionIsolationGood forWatch out for
Text editor and CyberChef on an analysis VMNo execution at allStatic decoding, beautifying, string extractionUse a local copy of CyberChef: it runs in the browser, but pasting samples into a hosted copy on a corporate workstation is still poor hygiene
Linux analysis VM (for example REMnux)Hypervisor, Windows samples cannot run nativelyJavaScript emulation (box-js), static PowerShell decoding, network simulationShared folders and clipboard; snapshot before each sample
Windows SandboxHypervisor-based, discarded on closeQuick look at PowerShell behaviour with logging onNetworking is on by default; disable it in the .wsb configuration and map sample folders read-only. Requires Pro, Enterprise or Education editions
Dedicated Windows analysis VM with snapshotsHypervisor, host-only or simulated networkDynamic analysis with Sysmon, script block logging and process monitoringRevert after every run; never join it to the corporate domain or sign in with real credentials
Automated sandbox serviceProvider's environmentFast behavioural report at scaleUploading may disclose the sample or targeted data to third parties; follow your data handling rules
  • Network: host-only or no network by default. If you need to see callbacks, use a simulated internet service in the lab rather than real egress, and never let a sample reach the real download site from a corporate IP.
  • Handling: store samples in password-protected archives, rename extensions (for example .js_, .ps1_) so a double-click does nothing, and defang URLs in notes and tickets.
  • Identity: analysis machines use local, throwaway accounts with no access to production, mail or cloud consoles. A sample that steals tokens from the analyst's session turns triage into an incident.
  • Logging on the lab: enable PowerShell Script Block Logging and process creation logging inside the Windows lab so the sample decodes itself into the log while you watch.

Common JavaScript obfuscation patterns

Malicious JavaScript arrives as a standalone .js file run by Windows Script Host (wscript.exe or cscript.exe), embedded in HTML for smuggling, or injected into websites. Open-source obfuscators publish their transformations, which is a useful catalogue of what you will meet: the javascript-obfuscator project documents options such as stringArray, stringArrayRotate, stringArrayEncoding, splitStrings, controlFlowFlattening, deadCodeInjection, selfDefending and debugProtection.

PatternWhat it looks likeSafe way to reverse it
Encoding layersLong Base64, hex (\x41) or Unicode (A) escapes, atob or String.fromCharCode on number listsDecode the literal in CyberChef (From Base64, From Hex, From Charcode); the Magic operation suggests nested encodings
String splitting and concatenationKeywords built from fragments joined with +, join or concatBeautify, then join constant fragments by hand or with a deobfuscator
String array with rotationOne large array of encoded strings, a function that shuffles it at start-up, and calls like _0x3f2a(0x1b) everywhereTools such as synchrony target this format and resolve calls statically; check the result reads sensibly
Eval layeringA decoded string passed to eval, new Function, setTimeout with a string, or written into the page, repeated several timesIn an emulator or isolated VM, replace the sink with a print or logging call so each layer is shown, not run
Control flow flatteningA loop around a switch driven by a dispatcher string or array, hiding the real orderLet an AST-based deobfuscator simplify, or trace the dispatcher order by hand for short scripts
Dead code and junkUnused functions, opaque conditions that are always true or false, thousands of meaningless linesBeautify and search for sinks and ActiveX or WScript object creation; ignore the noise
Anti-analysisDebugger traps, timing checks, self-defending code that breaks when beautified, environment checks for sandbox artefactsPrefer emulation, which does not trip debugger traps; note the checks as behaviour

For Windows Script Host droppers, box-js emulates a Windows JScript environment and writes a results folder containing the executed code snippets (snippets.json), contacted URLs (urls.json), files written through ADODB streams (resources.json) and behaviours flagged as indicators (IOC.json). By default it simulates a 404 response rather than downloading payloads, which also reveals fallback URLs; its documentation recommends running it inside a temporary container for further isolation. See the HTML Smuggling Guide for the browser delivery variant.

Common PowerShell obfuscation patterns

PowerShell is forgiving about syntax, which makes it easy to obfuscate: cmdlet names are case insensitive, aliases abound, and almost anything can be built as a string and evaluated.

PatternWhat it looks likeSafe way to reverse it
Encoded command-EncodedCommand or a short prefix of it, followed by Base64 of UTF-16LE textCyberChef: From Base64 then Decode text (UTF-16LE); never paste it back into a shell
Inner Base64 and compressionFromBase64String with GzipStream, DeflateStream or MemoryStreamCyberChef: From Base64 then Gunzip or Raw Inflate; repeat per layer
String concatenation, reordering and replaceFragments joined with +, format operator -f with shuffled indexes, -replace or .Replace() chains, reversed stringsResolve constant expressions by reading, or in an isolated lab assign the final string to a variable and print it instead of evaluating
Character tricksBackticks inside names, random case, [char] arrays, -join, -bxor loopsRemove backticks and normalise case for reading; decode character arrays and XOR in CyberChef
Invoke-Expression layeringInvoke-Expression, its alias iex, the call operator &, dot sourcing, [scriptblock]::Create, often with the name itself obfuscatedIdentify the sink, then in the lab substitute an output call for it so each layer prints; PSDecode works by overriding these functions, and its author warns to run it only in an isolated sandbox
Living off the land wrappersPowerShell launched by mshta, wscript, rundll32 or an Office macro, or environment variables holding the payloadReconstruct the parent command line from process creation logs; see How to Hunt for Living-off-the-Land Binary Abuse

A static-first workflow that works for both languages

  1. Record and hash. Compute hashes, note source, delivery path and first-seen time, and check internal telemetry and threat intelligence for prior sightings.
  2. Check host telemetry first. If the script ran anywhere, pull PowerShell 4104 events and EDR or AMSI detections for that host and time; the decoded layer may already be there.
  3. Beautify and survey. Reformat the code, list long literals, find the sinks, find object creation (WScript.Shell, MSXML2.XMLHTTP, ADODB.Stream, Net.WebClient).
  4. Decode literals statically. Work outside in with CyberChef, saving each recipe so the next sample of the family is a one click job.
  5. Neutralise sinks, then emulate. Only when static work stalls, run the modified script in box-js or the isolated Windows lab, with sinks replaced by print statements and no real network.
  6. Extract and act. Pull URLs, domains, file paths, registry keys and scheduled task names; block and hunt for them; map behaviour to ATT&CK; write or tune a detection.
  7. Revert the lab. Restore the snapshot or close the sandbox before the next sample.

Tools and logging that help

Script Block Logging

Microsoft's documentation states that when Script Block Logging is enabled, PowerShell records the content of all script blocks that it processes, as event ID 4104. Because each layer that is evaluated becomes a script block, the log often contains every intermediate stage, ending with the plain code. Details are covered in the PowerShell Logging Detection Guide; the essentials for analysts are below.

ItemWindows PowerShell 5.1PowerShell 7
Event logMicrosoft-Windows-PowerShell/OperationalPowerShellCore/Operational
Event4104, script block text4104, script block text
Group PolicyAdministrative Templates, Windows Components, Windows PowerShell, Turn on PowerShell Script Block LoggingAdministrative Templates, PowerShell Core, Turn on PowerShell Script Block Logging
Registry valueHKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging, EnableScriptBlockLogging = 1HKLM\Software\Policies\Microsoft\PowerShellCore\ScriptBlockLogging, EnableScriptBlockLogging = 1

Large script blocks are split across several 4104 events, so reassemble them by script block ID before reading. Script block text can contain secrets that administrators passed in scripts; Microsoft's Protected Event Logging setting (Windows Components, Event Logging, Enable Protected Event Logging) encrypts the content with a Document Encryption certificate using CMS, with the private key kept off the logging machines.

AMSI

The Antimalware Scan Interface lets script hosts hand content to the installed anti-malware product before it runs. Microsoft lists the integrated Windows components as User Account Control, PowerShell (scripts, interactive use and dynamic code evaluation), Windows Script Host (wscript.exe and cscript.exe), JavaScript and VBScript, and Office VBA macros. The key point for analysts is Microsoft's own: a script may go through several passes of deobfuscation, but it ultimately has to supply the engine with plain code, and that is when AMSI is called, even for code generated at runtime. AMSI detections in your EDR or Defender console therefore often show the decoded content or a precise detection name, which can save hours of manual peeling. Attempts to tamper with AMSI are themselves a strong signal worth detecting.

Tool roles

ToolRoleExecutes sample?
CyberChef (GCHQ)Browser-based decoding: Base64, hex, XOR, compression, character encodings; Magic auto-detection, breakpoints and step-through; saved recipesNo
Code beautifier in your editorReadable layout before anything elseNo
synchronyAST-based cleaner for javascript-obfuscator outputNo (static transforms)
box-jsEmulates a Windows JScript environment and logs snippets, URLs, files and indicatorsEmulated, run in a container
PSDecodeIntercepts PowerShell evaluation functions and prints each layerYes, isolated lab only
REMnuxLinux distribution bundling free malware analysis toolsPlatform
Windows Sandbox or analysis VM with Sysmon and 4104 loggingControlled dynamic run with full telemetryYes, isolated

For compiled second stages that fall out of a script, continue in the Ghidra for Malware Analysis Guide. If you use AI assistants to explain decoded code, follow the data handling advice in AI-assisted reverse engineering for defenders.

Detection and measurement

  • Coverage: share of Windows endpoints and servers sending 4104 events to the SIEM, for both 5.1 and PowerShell 7 channels.
  • Time to decoded indicators: median time from sample receipt to extracted URLs and hashes being blocked.
  • Recipe reuse: share of samples decoded with an existing saved recipe or script, a sign the team is learning families.
  • Detection yield: new or tuned detections written per month from deobfuscation findings.
  • Lab hygiene: zero incidents of samples executed outside the lab, and every dynamic run followed by a revert.

Framework mapping

FrameworkReferenceRelevance
MITRE ATT&CK v20T1027, T1027.010, T1140The obfuscation and decoding behaviours analysed
MITRE ATT&CK v20T1059.001, T1059.007, T1204.002The execution these scripts lead to
NIST SP 800-53 Rev 5SI-3, SI-4, AU-2Malicious code protection, system monitoring, event logging
NIST CSF 2.0DE.AE-02, RS.AN-03Analysing adverse events and establishing what happened

Common failure patterns

  • Running the sample to "see what it does": double-clicking a .js file or pasting a decoded line into a live PowerShell session on an analyst workstation. This is how triage becomes compromise.
  • Uploading before thinking: submitting a targeted sample to a public sandbox, which can tip off the actor or disclose embedded internal data.
  • Peeling by hand what the host already logged: spending hours on layers while 4104 events or AMSI detections for the same execution sit unread.
  • Script Block Logging on only one PowerShell edition: policy set for Windows PowerShell but not PowerShell 7 (or the reverse), so one channel is silent.
  • Stopping at the first URL: extracting one download URL and missing the fallback list, persistence and second stage.
  • Not saving recipes: every sample of a family decoded from scratch, so analysis time never falls.

Practitioner checklist

  • Build an isolated lab: Linux analysis VM plus a Windows VM or Windows Sandbox, no production network, snapshots, throwaway local accounts.
  • Store samples in protected archives with neutralised extensions, and defang all indicators in notes.
  • Enable Script Block Logging for both Windows PowerShell and PowerShell 7 fleet-wide, and forward 4104 to the SIEM.
  • Check 4104 events and AMSI detections for the affected host before starting manual analysis.
  • Work static first: beautify, find sinks, decode literals in CyberChef, save recipes.
  • Emulate JavaScript with box-js in a container before considering any real execution.
  • Replace execution sinks with output calls before any dynamic run, and revert the lab after each one.
  • Turn findings into blocks, hunts, ATT&CK mappings and at least one detection improvement.

Standards and references

Related NHI Mgmt Group resources: PowerShell Security Guide · PowerShell Logging Detection Guide · T1027 Obfuscated Files or Information Defensive Guide · HTML Smuggling Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.