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,Functionor a WScript call; PowerShell funnels intoInvoke-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.
| Option | Isolation | Good for | Watch out for |
|---|---|---|---|
| Text editor and CyberChef on an analysis VM | No execution at all | Static decoding, beautifying, string extraction | Use 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 natively | JavaScript emulation (box-js), static PowerShell decoding, network simulation | Shared folders and clipboard; snapshot before each sample |
| Windows Sandbox | Hypervisor-based, discarded on close | Quick look at PowerShell behaviour with logging on | Networking 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 snapshots | Hypervisor, host-only or simulated network | Dynamic analysis with Sysmon, script block logging and process monitoring | Revert after every run; never join it to the corporate domain or sign in with real credentials |
| Automated sandbox service | Provider's environment | Fast behavioural report at scale | Uploading 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.
| Pattern | What it looks like | Safe way to reverse it |
|---|---|---|
| Encoding layers | Long Base64, hex (\x41) or Unicode (A) escapes, atob or String.fromCharCode on number lists | Decode the literal in CyberChef (From Base64, From Hex, From Charcode); the Magic operation suggests nested encodings |
| String splitting and concatenation | Keywords built from fragments joined with +, join or concat | Beautify, then join constant fragments by hand or with a deobfuscator |
| String array with rotation | One large array of encoded strings, a function that shuffles it at start-up, and calls like _0x3f2a(0x1b) everywhere | Tools such as synchrony target this format and resolve calls statically; check the result reads sensibly |
| Eval layering | A decoded string passed to eval, new Function, setTimeout with a string, or written into the page, repeated several times | In an emulator or isolated VM, replace the sink with a print or logging call so each layer is shown, not run |
| Control flow flattening | A loop around a switch driven by a dispatcher string or array, hiding the real order | Let an AST-based deobfuscator simplify, or trace the dispatcher order by hand for short scripts |
| Dead code and junk | Unused functions, opaque conditions that are always true or false, thousands of meaningless lines | Beautify and search for sinks and ActiveX or WScript object creation; ignore the noise |
| Anti-analysis | Debugger traps, timing checks, self-defending code that breaks when beautified, environment checks for sandbox artefacts | Prefer 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.
| Pattern | What it looks like | Safe way to reverse it |
|---|---|---|
| Encoded command | -EncodedCommand or a short prefix of it, followed by Base64 of UTF-16LE text | CyberChef: From Base64 then Decode text (UTF-16LE); never paste it back into a shell |
| Inner Base64 and compression | FromBase64String with GzipStream, DeflateStream or MemoryStream | CyberChef: From Base64 then Gunzip or Raw Inflate; repeat per layer |
| String concatenation, reordering and replace | Fragments joined with +, format operator -f with shuffled indexes, -replace or .Replace() chains, reversed strings | Resolve constant expressions by reading, or in an isolated lab assign the final string to a variable and print it instead of evaluating |
| Character tricks | Backticks inside names, random case, [char] arrays, -join, -bxor loops | Remove backticks and normalise case for reading; decode character arrays and XOR in CyberChef |
| Invoke-Expression layering | Invoke-Expression, its alias iex, the call operator &, dot sourcing, [scriptblock]::Create, often with the name itself obfuscated | Identify 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 wrappers | PowerShell launched by mshta, wscript, rundll32 or an Office macro, or environment variables holding the payload | Reconstruct 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
- Record and hash. Compute hashes, note source, delivery path and first-seen time, and check internal telemetry and threat intelligence for prior sightings.
- 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.
- Beautify and survey. Reformat the code, list long literals, find the sinks, find object creation (
WScript.Shell,MSXML2.XMLHTTP,ADODB.Stream,Net.WebClient). - Decode literals statically. Work outside in with CyberChef, saving each recipe so the next sample of the family is a one click job.
- 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.
- 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.
- 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.
| Item | Windows PowerShell 5.1 | PowerShell 7 |
|---|---|---|
| Event log | Microsoft-Windows-PowerShell/Operational | PowerShellCore/Operational |
| Event | 4104, script block text | 4104, script block text |
| Group Policy | Administrative Templates, Windows Components, Windows PowerShell, Turn on PowerShell Script Block Logging | Administrative Templates, PowerShell Core, Turn on PowerShell Script Block Logging |
| Registry value | HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging, EnableScriptBlockLogging = 1 | HKLM\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
| Tool | Role | Executes sample? |
|---|---|---|
| CyberChef (GCHQ) | Browser-based decoding: Base64, hex, XOR, compression, character encodings; Magic auto-detection, breakpoints and step-through; saved recipes | No |
| Code beautifier in your editor | Readable layout before anything else | No |
| synchrony | AST-based cleaner for javascript-obfuscator output | No (static transforms) |
| box-js | Emulates a Windows JScript environment and logs snippets, URLs, files and indicators | Emulated, run in a container |
| PSDecode | Intercepts PowerShell evaluation functions and prints each layer | Yes, isolated lab only |
| REMnux | Linux distribution bundling free malware analysis tools | Platform |
| Windows Sandbox or analysis VM with Sysmon and 4104 logging | Controlled dynamic run with full telemetry | Yes, 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
| Framework | Reference | Relevance |
|---|---|---|
| MITRE ATT&CK v20 | T1027, T1027.010, T1140 | The obfuscation and decoding behaviours analysed |
| MITRE ATT&CK v20 | T1059.001, T1059.007, T1204.002 | The execution these scripts lead to |
| NIST SP 800-53 Rev 5 | SI-3, SI-4, AU-2 | Malicious code protection, system monitoring, event logging |
| NIST CSF 2.0 | DE.AE-02, RS.AN-03 | Analysing adverse events and establishing what happened |
Common failure patterns
- Running the sample to "see what it does": double-clicking a
.jsfile 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
- Microsoft Learn: about_Logging_Windows
- Microsoft Learn: about_Logging (Windows PowerShell 5.1)
- Microsoft Learn: Antimalware Scan Interface (AMSI)
- Microsoft Learn: How AMSI helps you defend against malware
- MITRE ATT&CK: T1027.010 Command Obfuscation
- Microsoft Learn: Windows Sandbox overview
- GCHQ: CyberChef
- box-js: A utility to analyze malicious JavaScript
Related NHI Mgmt Group resources: PowerShell Security Guide · PowerShell Logging Detection Guide · T1027 Obfuscated Files or Information Defensive Guide · HTML Smuggling Guide