Hunting with Elastic Security: Detecting command and scripting interpreter execution

Blog_Header_Image-_ELK_Hunting_Series-4-178628.jpg

Stealthy adversaries continually exploit system utilities to execute malicious code. A particularly potent and frequently misused tactic is MITRE ATT&CK® T1059 - Command and Scripting Interpreter, wherein attackers harness built-in interpreters like PowerShell, Bash, Python, or JavaScript to run arbitrary commands. This strategy enables adversaries to conduct reconnaissance, escalate privileges, and move laterally within an environment — all while camouflaging their activities amid legitimate operations.

Hunting with Elastic Security

Script execution is pervasive in many environments — administrators automate tasks, developers deploy scripts, and various services execute commands. However, the ubiquity of this script execution presents a challenge of distinguishing between benign activities and potential threats. Could a seemingly innocuous PowerShell script be exfiltrating sensitive data? Is a batch file surreptitiously disabling security controls? 

Attackers adeptly leverage command and scripting interpreters to fulfill their objectives. The critical question arises: Can you detect their activities before they establish persistence and seize control, or will their malicious scripts evade detection? The hunt begins now.

Understanding the technique

T1059 - Command and Scripting Interpreter falls under the Execution tactic in the MITRE ATT&CK framework. This technique encompasses various script-based execution methods, including:

  • T1059.001 - PowerShell: Adversaries use PowerShell to execute payloads, modify system configurations, or evade defenses.

  • T1059.002 - AppleScript: Used on macOS systems for execution and automation.

  • T1059.003 - Windows Command Shell: Attackers leverage cmd.exe to execute batch scripts or system commands.

  • T1059.004 - Unix Shell: Bash or other shells are used for execution on Linux/macOS.

  • T1059.005 - Visual Basic: VBScript execution in legacy environments.

  • T1059.006 - Python: Attackers use Python scripts to deploy malware or automate tasks.

  • T1059.007 - JavaScript/JScript: Execution via JavaScript for initial access or payload execution.

Failure to detect unauthorized script execution can lead to privilege escalation, lateral movement, and complete system compromise. Defenders must monitor script execution closely to separate benign administrative activity from potential adversarial behavior.

Data sources to optimize the hunt

To detect adversarial use of scripting interpreters, we rely on several key data sources. These are enriched and normalized through the Elastic Common Schema (ECS), allowing for consistent analysis and cross-source correlation:

1. Network traffic logs: Identifies when interpreters initiate network connections, which may indicate data exfiltration, remote command and control, or script-based downloaders.

  • Elastic integration: For network logs, you can leverage one of Elastic’s many integrations. Most firewall integrations will ingest the required data correctly. You could also utilize the Network Packet Capture to capture and analyze network traffic.

2. Process monitoring logs: Reveal when interpreters like powershell.exe, cmd.exe, bash, or python are launched, and show command-line arguments. These logs are foundational for identifying suspicious script activity.

  • Elastic integration: Elastic Agent can be configured with centrally managed  integrations and ship system telemetry logs to Elastic.

3. File monitoring: Helps detect when script files (e.g., .ps1, .bat, .vbs) are created, modified, or executed. This can expose attempts to persist scripts or load them from unusual locations.

  • Elastic integration: File Integrity Monitoring, Windows, Auditd

4. Proxy logs: Helps detect exfiltration via HTTPS by monitoring suspicious traffic patterns.

  • Elastic integration: You can leverage one of Elastic’s many integrations to collect proxy logs.

Threat hunting with ES|QL queries

To detect adversaries exploiting T1059 - Command and Scripting Interpreter, we analyze process executions, script activities, and command-line behaviors for signs of unauthorized command execution. Utilizing the ECS, these diverse data sources are parsed and normalized into a consistent format, enabling effective correlation and detection across various logs. Below are ES|QL queries designed to detect specific aspects of this technique, utilizing ECS fields to streamline analysis and enhance threat-hunting capabilities.

1. Detect PowerShell encoded commands

FROM logs-*
| WHERE process.command_line LIKE "*powershell*EncodedCommand*"
| KEEP process.command_line, user.name, host.name, @timestamp

Explanation: This query detects PowerShell commands using the EncodedCommand flag, commonly used by attackers to obfuscate malicious payloads. While this technique can be used legitimately, frequent or unexpected use (especially outside admin contexts) may warrant investigation.

2. Identify unusual interpreter usage

FROM logs-*
| WHERE process.name IN ("python", "bash", "cmd.exe", "powershell.exe", "wscript.exe", "cscript.exe")
| STATS count = COUNT() BY process.name, user.name, host.name

Explanation: This query highlights usage of interpreters to help identify potentially suspicious patterns of use, such as scripts running under accounts or on systems that don’t typically use them. While manual baselining across departments and roles is valuable, machine learning models can take this further by dynamically learning what "normal" interpreter usage looks like in your environment. Leveraging Elastic's built-in machine learning can help automate anomaly detection, flagging deviations in real time and reducing false positives while scaling your hunt across large datasets.

3. Detect process creation with suspicious command line

FROM logs-*
| WHERE process.command_line LIKE "*Invoke-WebRequest*" OR process.command_line LIKE "*IEX*"
| KEEP process.command_line, user.name, host.name, @timestamp

Explanation: This query detects PowerShell commands commonly used to download remote payloads or run inline scripts. These functions (e.g., Invoke-WebRequest, IEX) are frequently used in offensive tooling and malware delivery. To reduce false positives, validate whether such commands are used within scheduled tasks or known administrative scripts. Correlate this with user behavior and time of execution to determine legitimacy.

4. Identify Bash script execution on Linux

FROM logs-*
| WHERE process.name == "bash"
  AND process.command_line LIKE "*curl*"
| KEEP process.name, process.command_line, user.name, host.name, @timestamp

Explanation: This query targets Bash script executions that invoke curl, a common technique adversaries use on Linux systems to download payloads or exfiltrate data during command and scripting interpreter abuse. While Bash and curl are frequently used for legitimate admin and automation tasks, their combined use — especially in unexpected contexts or by unauthorized users — can indicate script-based attack activity. To reduce false positives, analysts should baseline normal usage patterns and investigate anomalies.

5. Identify parent-child process relationships for scripts

FROM logs-*
| WHERE process.parent.name IN ("explorer.exe", "winword.exe")
  AND process.name IN ("powershell.exe", "cmd.exe")
| KEEP process.parent.name, process.name, process.command_line, host.name, @timestamp

Explanation: The query detects instances where scripting interpreters like PowerShell or CMD are launched by unexpected parent processes such as explorer.exe or winword.exe. While this behavior isn’t always malicious, it can indicate script execution triggered by user interaction with weaponized documents or deceptive UI elements. These parent-child relationships are often seen in phishing attacks or initial access attempts. Analysts should review the context carefully, as this pattern may also occur during legitimate automation or macro-enabled workflows — so there's some risk of false positives.

6. Identify use of curl or wget for downloads

FROM logs-*
| WHERE process.command_line LIKE "*curl*" OR process.command_line LIKE "*wget*"
| KEEP process.name, process.command_line, user.name, host.name, @timestamp

Explanation: This query detects the use of command-line tools like curl and wget, which adversaries often use to download payloads or exfiltrate data during script-based attacks. These tools are powerful but can be misused when executed from scripting interpreters like Bash or PowerShell. While curl and wget are legitimate utilities found in many environments, especially on Unix-like systems, their invocation in unusual contexts or by unexpected users can signal suspicious activity. Consider correlating with process parent relationships or execution timing to help reduce false positives.

7. Monitor for Python script execution

FROM logs-*
| WHERE process.name == "python"
| KEEP process.name, process.command_line, user.name, host.name, @timestamp

Explanation: This query monitors for the execution of Python scripts, which may be legitimate in development or automation contexts but can also be abused by adversaries for post-exploitation activities, such as payload deployment or data exfiltration. While Python is common in many environments, its presence on systems that typically do not run Python warrants investigation. Analysts should consider baselining expected Python usage to help reduce false positives and focus on suspicious or anomalous execution patterns.

6. Detect JScript or JavaScript execution

FROM logs-*
| WHERE process.name IN ("wscript.exe", "cscript.exe")
| KEEP process.name, process.command_line, user.name, host.name, @timestamp

Explanation: The query monitors for execution of scripts through wscript.exe and cscript.exe, which are native Windows scripting hosts used for running JScript and VBScript. These interpreters are often leveraged by adversaries to execute malicious scripts, especially during initial access or execution phases, making their detection critical for early threat identification.

7. Identify suspicious VBScript execution

FROM logs-*
| WHERE process.name == "wscript.exe"
  AND process.command_line LIKE "*.vbs"
| KEEP process.name, process.command_line, user.name, host.name, @timestamp

Explanation: This query detects instances where the Windows Script Host (wscript.exe) is used to execute VBScript files (.vbs). While VBScript can be employed for legitimate automation tasks, its misuse is a common tactic among adversaries to execute malicious code, often leading to unauthorized actions such as data exfiltration or system compromise. By monitoring for the execution of .vbs files through wscript.exe, security teams can identify and investigate potentially malicious script activities.

8. Detect execution from temporary directories

FROM logs-*
| WHERE file.path LIKE "C:\\\\Users\\\\*\\\\AppData\\\\Local\\\\Temp\\\\*"
  AND process.name IN ("powershell.exe", "cmd.exe", "python")
| KEEP process.name, process.command_line, file.path, user.name, host.name, @timestamp

Explanation: This query detects the execution of scripting interpreters — such as PowerShell (powershell.exe), Command Prompt (cmd.exe), and Python (python) — from within the Temp directories of user profiles (C:\Users\<User>\AppData\Local\Temp\). Temporary directories are frequently used by both legitimate applications and malicious software to store and execute files. However, the execution of scripts from these locations can be indicative of unauthorized or malicious activity, as adversaries often leverage temporary folders to deploy and run malicious scripts to evade detection.

9. Detect execution of suspicious batch scripts

FROM logs-*
| WHERE process.name == "cmd.exe"
  AND process.command_line LIKE "*.bat"
| KEEP process.name, process.command_line, user.name, host.name, @timestamp

Explanation: This query detects instances where the Windows Command Prompt (cmd.exe) is used to execute batch scripts, which are files with a .bat extension containing a series of commands for the system to execute. While batch scripts are commonly utilized for legitimate administrative tasks, their misuse can indicate malicious activities, such as the automation of harmful commands or system configuration alterations.

10. Monitor for unusual interpreter activity in critical directories

FROM logs-*
| WHERE process.name IN ("bash", "python", "powershell", "cmd.exe")
  AND file.path LIKE "C:\\\\Windows\\\\System32\\\\*"
| KEEP process.name, process.command_line, file.path, user.name, host.name, @timestamp

Explanation: This query detects the execution of scripting interpreters — such as Bash, Python, PowerShell, or Command Prompt (cmd.exe) — within the critical C:\Windows\System32\ directory on Windows systems. The System32 folder is integral to the operating system, housing essential system files and executables. While legitimate processes often operate within this directory, adversaries may exploit it to execute malicious scripts, leveraging the inherent trust and functionality of system binaries. By monitoring interpreter activities in this location, security teams can identify potential misuse or unauthorized operations that could signify attempts to compromise the system.

11. Detect Base64 or obfuscated PowerShell strings

FROM logs-*
| WHERE process.command_line LIKE "*powershell*" AND process.command_line LIKE "*Base64*"
| KEEP process.command_line, user.name, host.name, @timestamp

Explanation: This query is designed to detect instances where PowerShell commands are executed with Base64-encoded arguments, a common technique used by adversaries to obfuscate malicious payloads and evade detection mechanisms.

12. Find multiple script executions in short timeframe

FROM logs-*
| WHERE process.name IN ("powershell.exe", "cmd.exe", "bash", "python")
| EVAL bucket = DATE_TRUNC( 60 minute, @timestamp)
| STATS executions = COUNT() BY user.name, process.name, bucket
| WHERE executions >= 10

Explanation: This ES|QL query identifies instances where scripting interpreters — such as PowerShell, Command Prompt (cmd.exe), Bash, or Python — are executed multiple times within a short timeframe by the same user. Such patterns may indicate automated scripts, potential malware activity, or unauthorized tasks being performed.

Threat hunting with ES|QL queries

The hunt for unauthorized command and scripting interpreter usage has concluded. Did your investigation reveal any covert executions of malicious scripts, or did your defenses stand resilient against such exploitation? By scrutinizing command-line activities, monitoring script executions, and analyzing process behaviors, you've illuminated potential pathways adversaries might exploit to execute unauthorized commands within your systems.

If you've uncovered indicators of Technique T1059 - Command and Scripting Interpreter misuse, you've taken pivotal steps toward thwarting adversaries from leveraging these tools for malicious purposes, thereby safeguarding your organization's critical assets. If no such signs were found, your proactive measures have validated the robustness of your defenses against this prevalent threat vector. 

To sustain and scale this vigilance, consider converting these ES|QL queries into detection rules — paired with Elastic’s machine learning jobs — to baseline interpreter behavior and automate anomaly detection. This transformation elevates your hunt into a continuous defense strategy, keeping your organization resilient against evolving threats.

Elevate your threat-hunting capabilities by exploring the latest resources at Elastic Security Labs. Our newly released hunting package offers specialized detection queries across various platforms, empowering you to proactively identify and mitigate threats. Dive into our comprehensive collection and enhance your security posture today.

The logs don’t lie — let them guide your hunt.

The release and timing of any features or functionality described in this post remain at Elastic's sole discretion. Any features or functionality not currently available may not be delivered on time or at all.