- Home
- SIEM use cases
- Automated file system enumeration
Automated file system enumeration
In this page
- Threat snapshot
- How this attack works
- Attack chain
- Real-world scenario
- Business impact: What can go wrong
- Indicators of compromise and detection signals
- Prerequisites for detection using Log360
- Detecting automated file system enumeration using Log360
- Investigating an alert
- Responding and remediating
- False positive guidance
- Hardening and prevention
Threat snapshot
Before an attacker can steal data, they need to know where it is. File system enumeration is the reconnaissance phase of data collection: systematically traversing directory trees to build a map of what files exist, where they are stored, and which ones are worth targeting. In Windows environments, the cmd.exe for loop combined with the /r flag for recursive directory search is one of the most direct ways to perform this enumeration entirely within native Windows tooling, without downloading or running any external utility.
The specific command construct this rule targets uses cmd.exe's built-in for /r loop to walk a directory tree recursively, outputting file names, paths, or sizes. It is a legitimate batch scripting construct that appears in backup scripts, inventory tools, and file management utilities. It is also used by attackers who want to identify valuable files on a compromised host or network share before staging them for exfiltration. Log360 detects this activity through the Suspicious Usage of For Loop with Recursive Directory Search in CMD rule, which monitors for cmd.exe invocations carrying the for /r pattern in their command-line arguments. The signal value comes from context: who is running it, from what session, against what path, and in combination with what other post-exploitation activity.
At a glance
| Category | Endpoint Threat |
|---|---|
| SOC maturity level | L2 - Investigation |
| MITRE ATT&CK tactic | TA0009 - Collection |
| MITRE ATT&CK technique | T1083 | File and Directory Discovery |
| Severity | Attention |
| Affected platforms | Windows |
| Detection rule | Suspicious Usage of For Loop with Recursive Directory Search in CMD |
| Compliance mapping | NIST SP 800-53 AU-12, ISO 27001 A.12.4, SOC 2 CC7.2, PCI DSS 10.6 |
How this attack works
The cmd.exe for loop with the /r flag provides a native Windows mechanism for recursive directory traversal. The core pattern takes the following form:
for /r <path> %f in (<filter>) do <command>
-- common attacker variants --
for /r C:\ %f in (*.docx *.xlsx *.pdf) do echo %f >> C:\Temp\filelist.txt
for /r \\server\share %f in (*) do @echo %~z %~f >> files.txt
for /r %USERPROFILE% %f in (*.pst *.ost *.kdb) do copy %f C:\Temp\
The /r flag instructs the for loop to recurse into all subdirectories of the specified root path. The filter expression in parentheses can specify file extensions, patterns, or wildcards. The command executed for each matching file can be anything: outputting to a file, copying, compressing, or simply printing the path.
In an attack context, this construct is used for three distinct purposes. File discovery enumerates specific file types across the system or a network share, building a list of valuable targets before staging. File collection uses the loop to directly copy matching files to a staging directory for later compression and exfiltration. Credential file hunting uses specific extension patterns such as .kdbx (KeePass), .pst (Outlook mail archive), .pfx (certificate with private key), or .config (application configuration, potentially containing credentials) to find credential-bearing files specifically.
The technique requires no special tools, no downloaded binaries, and leaves no installation artefact. It uses only cmd.exe, which is present on every Windows installation and whose execution is routine in enterprise environments. The detection relies entirely on the command-line arguments containing the for /r pattern, which is why command-line logging is a prerequisite.
Why the for /r pattern is used rather than PowerShell
PowerShell's Get-ChildItem -Recurse is functionally equivalent and more powerful. Attackers who specifically choose the cmd.exe for /r pattern over PowerShell are either operating in an environment where PowerShell execution is restricted, are using a tool or script that generates cmd.exe-based commands, or are deliberately choosing a command format that generates fewer logs in environments where PowerShell Script Block Logging is enabled but cmd.exe command-line logging is not. The choice of for /r in cmd.exe over PowerShell is a defence-awareness signal in itself.
Attack chain
The table below maps automated file system enumeration to its position in a typical intrusion sequence and its corresponding MITRE ATT&CK technique.
| Stage | What happens | MITRE ID |
|---|---|---|
| Initial access and persistence | Attacker establishes and maintains a foothold on a Windows endpoint under a compromised user or service account. | T1078 / T1547 |
| Discovery: system enumeration | Attacker runs basic discovery commands to understand the host: whoami, ipconfig, net user, systeminfo, establishing the environment context. | T1033 / T1082 |
| Collection: file system enumeration | cmd.exe for /r loop executed to recursively traverse one or more directory trees, outputting file paths matching specific extensions or patterns to a staging file or to stdout. | T1083 |
| Collection: targeted file copying | For /r loop used to directly copy matched files to a staging directory, or the enumeration output is used to build a targeted copy list that is executed in a subsequent step. | T1005 / T1039 |
| Staging | Collected files are compressed using 7-Zip or another archiving tool, often with password encryption, preparing the data for exfiltration. | T1560.001 |
| Exfiltration | Staged archives transferred to attacker-controlled infrastructure via HTTPS, SMB, or C2 channel. | T1041 / T1048 |
Real-world scenario
A legal firm stores client matter files, contracts, and correspondence in a structured share on a Windows file server, organised by matter number and client name. A threat actor who has been operating inside the network for six days using a compromised paralegal account has identified the file server share path and wants to understand its structure before staging a targeted collection.
From a remote command prompt session on the paralegal's workstation, the attacker runs two for /r commands in sequence. The first traverses the mapped network share recursively, filtering for .docx, .pdf, and .xlsx files, and redirects the output to a file named index.txt in the user's AppData directory. The command runs for approximately four minutes before completing, producing a file listing of 47,000 documents across 312 directories. The second command is a targeted copy: a for /r loop filtering for files whose paths contain the word confidential or settlement, copying those files directly to a staging directory.
Log360 fires the for /r enumeration alert 30 seconds after the first command begins executing. The SOC analyst reviewing the alert notes the network share path in the command-line arguments and the output redirection to an AppData file. They query for other discovery commands from the same account in the preceding 30 minutes and find whoami, ipconfig, and net use commands confirming a systematic post-exploitation sequence. The host is isolated and the staged files are found in the AppData staging directory before they can be archived and exfiltrated.
Why this happens
The for /r loop in cmd.exe generates a single process creation event for the cmd.exe process carrying the loop in its command line. It does not spawn child processes for each file it visits. It does not write any files unless explicitly redirected. It leaves no artefact in the file system unless the output is redirected to a file. Without process creation auditing with command-line logging, it generates no observable signal at all. Even with command-line logging enabled, a for /r loop running against a network share from a user's normal workstation session can appear routine without context about what other commands preceded it.
Business impact: What can go wrong
Automated file system enumeration itself does not steal data, but it is the reconnaissance phase that makes targeted data theft possible and efficient:
- Targeted data exfiltration: enumeration that produces a file listing of an entire file server allows an attacker to identify and selectively collect only the highest-value files rather than blindly copying everything. This makes the exfiltration faster, less voluminous, and harder to detect via data volume anomalies.
- Credential file discovery: for /r loops that specifically target file extensions associated with credential stores (.kdbx, .pst, .pfx, .p12, .config, .env, .xml) are designed to locate credential-bearing files for targeted collection. A single KeePass database or a certificate with a private key can provide broader access than any other single file on the system.
- Intellectual property mapping: organisations whose competitive value is in their documents, designs, or research are particularly exposed to systematic enumeration. A structured output of all documents on a file server gives the attacker a complete picture of what intellectual property exists before they decide what to steal.
- Ransomware preparation: ransomware operators use file system enumeration to identify the most valuable directories to prioritise during encryption, ensuring that the files most critical to the organisation are encrypted first rather than last.
- Double extortion data inventory: in double extortion ransomware scenarios, the attacker needs to demonstrate they have stolen valuable data to make the extortion threat credible. Systematic enumeration before exfiltration ensures the attacker has a verifiable inventory of what was taken.
- Delayed discovery: enumeration output written to a staging file may persist on the system for days or weeks before being used. Even if the immediate exfiltration attempt is interrupted, a cached file listing of the network share remains available for later collection attempts.
Indicators of compromise and detection signals
| Signal type | What to look for |
|---|---|
| Process and command line | cmd.exe executed with command-line arguments containing for and /r, indicating a recursive for loop. The root path, file filter pattern, and the action applied to each matching file are all visible in the command line and are the primary triage fields. |
| Root path targeted | The path specified as the root of the recursive search. A root path pointing to a network share (beginning with two backslashes), a drive root such as C:\, or a sensitive path such as a user's Documents folder or a shared data directory is higher confidence than a path within a documented script's working directory. |
| File extension filter | The filter pattern in the for loop's parentheses. Filters targeting document formats (.docx, .xlsx, .pdf), credential files (.kdbx, .pst, .pfx, .p12, .env), or database files (.mdf, .bak, .sql) indicate targeted data collection. A wildcard (*) filter targeting a sensitive root path indicates broad enumeration before targeted collection. |
| Output redirection | The command applied to each matching file. Redirection to a file (>> filename.txt or > filename.txt) indicates the attacker is building a file listing for later use. A copy command indicates immediate collection. Both are higher confidence than simple echo or dir output to stdout. |
| Event IDs | 4688 (Process Create): cmd.exe with for /r in the ProcessCommandLine field. Sysmon Event ID 1 for enriched process context including parent process chain and full command line. |
| Discovery command clustering | For /r enumeration appearing within 120 seconds of other discovery commands on the same host: whoami, ipconfig, net use, net view, systeminfo, or dir commands targeting sensitive paths. A cluster of discovery commands including file enumeration is a high-confidence post-exploitation indicator. |
| Output file creation | Sysmon Event ID 11 (File Create): a text or log file created in AppData, Temp, or a user-writable path following the for /r command, which may contain the enumeration output. |
Prerequisites for detection using Log360
Before the Suspicious Usage of For Loop with Recursive Directory Search in CMD rule can fire reliably, ensure the following are in place:
- Windows Process Creation auditing with command-line logging is enabled on all monitored endpoints, generating Event ID 4688 with the full ProcessCommandLine field populated. This is the only detection path for this rule. The for /r pattern exists entirely within the cmd.exe command-line arguments. Without command-line logging, cmd.exe process creation events will appear in the log but the /r flag, the root path, and the file filter will not be captured, making the alert impossible to fire.
- Sysmon is deployed on all monitored endpoints with a configuration capturing Event ID 1 (Process Create). Sysmon provides the parent process chain, which is essential for determining whether the for /r command was run interactively from an admin session, from a script, or from a malware process. Sysmon Event ID 11 (File Create) provides the secondary signal of any output file created by the enumeration command.
- Endpoint agents or Windows Event Forwarding are configured to forward Security and Sysmon logs from all monitored endpoints to Log360. File system enumeration occurs on individual endpoints or from workstations accessing network shares. Coverage must include all workstations and file servers.
Note: The for /r loop command may be executed inline from a cmd.exe session or embedded in a batch file. When embedded in a batch file, the process creation event will show cmd.exe executing the batch file rather than the for loop directly. Depending on how the batch file is invoked, the command-line logging may capture the for loop syntax from the batch file execution context or only the batch file invocation. Sysmon Event ID 1 with full command-line capture is more reliable for catching embedded batch file execution of recursive loops than Windows Security Event ID 4688 alone.
Detecting automated file system enumeration using Log360
Once log collection is configured, follow these steps to enable and tune detection in Log360:
Step 1: Enable the detection rule
Navigate to Security > Manage Rules > Rule Library in the Log360 console. Install and enable the rule: Suspicious Usage of For Loop with Recursive Directory Search in CMD. Configure an alert profile for the same. Set the severity to Attention, reflecting the moderate false positive surface of this rule.
Step 2: Read the alert
When the rule fires, the alert will display the hostname, the account that ran cmd.exe, the full command line including the for /r pattern, the root path, the file filter, and the action applied to matches, the parent process, and the timestamp. Review the root path first: a network share path is the highest priority. Then review the file filter: credential file extensions raise the priority regardless of the root path. Then review the parent process: an unusual or unknown parent process in a user-writable path is high confidence malicious, while a scheduled task or known management tool is lower confidence.
Investigating an alert
When the Suspicious For Loop rule fires, an L1 or L2 analyst should work through the following steps:
- Analyse the command line fully. From the alert detail, extract the root path being enumerated, the file extension filter, and the command applied to each matching file. A root path pointing to a sensitive network share combined with a credential file extension filter and output redirection to a file is a high-confidence attack indicator that warrants immediate escalation. A single extension filter against a home directory with stdout output is lower confidence.
- Check for a discovery command cluster. Query Log360 for all process creation events on the same host in the 120 seconds before and after the for /r command. Look for preceding discovery commands: whoami, ipconfig, net use, net view, dir, systeminfo, or tasklist. A sequence of multiple discovery commands with the for /r loop as the file-focused step is a strong post-exploitation enumeration pattern.
- Check for an output file. If the command redirected output to a file, query Log360 for Sysmon Event ID 11 (File Create) on the same host for the destination file path. If the file was created, its size gives an indication of how much enumeration output was produced. A large text file in AppData or Temp is significant evidence.
- Check for subsequent staging activity. Query Log360 for 7-Zip process creation events (7z.exe with archive arguments) on the same host in the 30 minutes following the for /r command. If the enumeration was followed by archiving activity, the data has been staged for exfiltration. Escalate immediately if archiving is confirmed.
- Assess the account and session context. Determine whether the account that ran the for /r command is the workstation's normal user, an administrative account, or a service account. Check the session type: an interactive local session is different in risk profile from a remote session from an unrecognised IP. If the session is remote, identify the source IP and verify it against documented administrator workstations or VPN exit nodes.
- Verify with the account owner. For named user accounts, contact the account owner to confirm whether they intentionally ran a recursive file search. IT administrators and developers sometimes run for /r loops for legitimate purposes. If the account owner cannot confirm the activity, treat the event as confirmed suspicious.
Escalation trigger
Escalate immediately to L2 or L3 if the root path targets a network share or a sensitive data directory; if the file filter targets credential file extensions (.kdbx, .pst, .pfx, .p12, .env, .config) or high-value document formats across a broad path; if the output was redirected to a file in AppData or Temp; if subsequent archiving or file copy commands are identified in the same session; or if a discovery command cluster preceded the for /r command. The combination of network share enumeration, credential file targeting, and subsequent staging is a confirmed pre-exfiltration sequence.
Responding and remediating
Immediate containment
- If the enumeration is confirmed as attacker-initiated and a staging file or collected files are present on the host, isolate the host from the network immediately. Network isolation prevents exfiltration of the collected data and severs any active remote session from which the enumeration was run.
- If an output file was created containing the enumeration results, preserve it before deletion as forensic evidence. The file listing reveals exactly what the attacker saw and may identify what data categories were targeted. Hash the file and document its path, size, and creation time.
- Disable the account that ran the for /r command if it is not a documented administrative account with a legitimate reason to enumerate the targeted path. Force a password reset and review all systems the account has authenticated to in the preceding 72 hours.
Forensic preservation
- Export the Windows Security event log and Sysmon operational log from the affected host covering the full discovery and enumeration session. These logs contain the complete command sequence from initial access through the file system enumeration step and any subsequent staging activity.
- If an output file listing was created, preserve and analyse it. The file listing establishes what the attacker now knows about the file server or local system, which informs the scope of the data at risk even if exfiltration has not been confirmed.
- Document the enumeration parameters: the root path, the file extensions targeted, and the volume of output produced. This information drives the breach assessment: if the attacker enumerated a share containing 50,000 documents filtered to .docx and .pdf, the scope of potentially identified data is defined by those parameters.
Eradication and recovery
- Remove any enumeration output files, staging files, and collected data files from the affected host. Verify none of the staging files have been transferred by checking network flow logs for outbound large transfers from the host following the enumeration.
- Rotate credentials for the compromised account and for any accounts whose credentials may have been accessible on the host or in files targeted by the enumeration. If credential file extensions were included in the filter pattern, treat any .kdbx, .pst, or .pfx files accessible from the enumerated path as potentially identified and assess whether the credentials they contain need to be rotated.
- Review access controls on the directories that were enumerated. If the attacker was able to enumerate a network share using a standard user account, assess whether that account should have access to the full directory tree or whether more granular access controls should be applied.
False positive guidance
The for /r construct in cmd.exe has legitimate uses in IT administration and automation. The following scenarios commonly produce false positive alerts:
- Backup verification scripts: IT teams that verify backup integrity by scanning for expected files often use for /r loops in batch scripts. These will run from a scheduled task or a service account at consistent times, target specific documented backup paths, and have a predictable output format. Verify the script source, the account running it, and the root path. If the path is a documented backup location and the account is a documented service account, create a scoped exclusion.
- Software deployment and compliance checks: deployment tools and compliance scanning scripts that verify file presence on endpoints may use for /r loops as part of their inventory or validation logic. These will originate from the management agent process rather than an interactive session and will target specific, documented directories. Verify the parent process is the documented management agent and create a scoped exclusion for that parent and path combination.
- Developer and power user file management: developers and power users who manage large file sets sometimes use for /r loops interactively for tasks like batch processing, renaming, or organising files. These will come from an interactive cmd.exe session from the user's own workstation during business hours, targeting the user's own directories rather than shared or system paths. Verify the user, the path, and the file filter. Targeting of the user's own local directories with a non-sensitive extension filter is likely legitimate.
- System administration inventory scripts: IT administrators who maintain file inventories or perform disk usage analysis may run for /r loops against file servers or local drives. Verify the administrator account, the business justification for the enumeration, and whether the activity aligns with a documented change ticket or operational task.
Key differentiator
Legitimate for /r loop executions are predictable, scoped to documented paths, run from known administrative accounts or documented automation processes, and do not appear alongside other post-exploitation discovery commands in the same session window. Attacker-initiated file system enumeration appears alongside other discovery commands (whoami, net use, ipconfig) in a short window, targets network shares or sensitive data paths rather than a specific known application directory, and often includes credential file extensions or broadly scoped wildcards against sensitive root paths. The combination of an unusual session context, a sensitive root path, and a credential-focused extension filter in the same command is the strongest differentiator.
Hardening and prevention
The following controls reduce the risk and detectability of automated file system enumeration in your environment:
- Apply the principle of least privilege to network share access. Users should have access to only the specific directories they need for their role. If a paralegal or standard business user account can enumerate a 47,000-file directory tree on a file server, the share permissions are broader than they need to be. Use NTFS permissions and share-level permissions together to scope access to specific subdirectories rather than root-level share access.
- Restrict execution of cmd.exe from user-writable directories via AppLocker or WDAC. If batch files and scripts in AppData or Temp cannot be executed directly via cmd.exe, the attacker cannot run a for /r loop from a malicious script in those locations. This does not prevent interactive cmd.exe use but eliminates the script-delivered variant of this technique.
- Enable file access auditing on sensitive directories. Windows Object Access auditing for file reads on high-value directories generates Event ID 4663 when files are accessed. Systematic read access to large numbers of files in a sensitive directory in a short window is a supporting indicator of enumeration or collection activity that complements the process-based detection.
- Enable PowerShell Script Block Logging and transcription on all endpoints. An attacker who uses PowerShell Get-ChildItem -Recurse instead of cmd.exe for /r will generate Script Block Log entries that provide the same detection signal through a different telemetry source. Broad logging coverage across both cmd.exe command-line and PowerShell script blocks reduces the attacker's ability to choose between logging blind spots.
- Implement DLP controls at the network egress layer that alert on large outbound transfers of document-type files. File system enumeration followed by collection and staging creates a downstream exfiltration event that generates a volume anomaly in egress traffic. Network-layer DLP that monitors outbound transfer volumes from endpoints that do not normally generate large uploads provides a backstop detection layer.


