Data Manipulation
Adversaries may insert, delete, or manipulate data in order to influence external outcomes or hide activity, threatening the integrity of the data. This technique encompasses three sub-techniques: Stored Data Manipulation (T1565.001), where adversaries directly alter files, databases, configuration data, or audit logs at rest; Transmitted Data Manipulation (T1565.002), where data is modified during transit via network interception or proxy manipulation; and Runtime Data Manipulation (T1565.003), where in-memory data structures or process state are altered during execution. Real-world examples include FIN13 (Elephant Beetle) injecting fraudulent financial transactions into compromised payment networks to incrementally siphon funds while mimicking legitimate processing behavior. Successful data manipulation campaigns often require prolonged access, domain-specific knowledge of the target system, and specialized tooling. The impact ranges from corrupted financial records and falsified audit trails to undermined operational decision-making and destroyed forensic evidence.
What is T1565 Data Manipulation?
Data Manipulation (T1565) maps to the Impact tactic — the adversary is trying to manipulate, interrupt, or destroy your systems and data in MITRE ATT&CK.
This page provides production-ready detection logic for Data Manipulation, covering the data sources and telemetry it touches: File: File Modification, File: File Creation, File: File Deletion, Windows: Security Event Log, Microsoft Defender for Endpoint. The queries below are rated high severity at medium confidence, and ship for 7 SIEM platforms — KQL, SPL, Elastic, QRadar, Sumo, YARA-L, LogScale.
MITRE ATT&CK
- Tactic
- Impact
- Technique
- T1565 Data Manipulation
- Canonical reference
- https://attack.mitre.org/techniques/T1565/
// T1565 — Data Manipulation
// Four-branch detection: audit log clearing, database file tampering,
// bulk file modification bursts, critical path tampering by unexpected processes
let ScriptingEngines = dynamic([
"powershell.exe", "cmd.exe", "wscript.exe", "cscript.exe",
"mshta.exe", "python.exe", "python3.exe", "perl.exe",
"php.exe", "node.exe", "ruby.exe", "bash", "sh"
]);
let DatabaseExtensions = dynamic(["mdf", "ldf", "db", "sqlite", "accdb", "mdb", "sql", "bak", "dbf", "frm"]);
let CriticalLogPaths = dynamic([
"\\windows\\system32\\winevt\\logs",
"\\inetpub\\logs",
"\\program files\\microsoft sql server",
"\\windows\\system32\\config"
]);
let LegitFileActors = dynamic([
"svchost.exe", "wininit.exe", "lsass.exe", "services.exe",
"csrss.exe", "MsMpEng.exe", "sqlservr.exe", "sqlagent.exe",
"taskhostw.exe", "TrustedInstaller.exe", "TiWorker.exe"
]);
// Branch 1: Windows Security/System Audit Log Cleared (Event ID 1102 = Security, 104 = System)
let AuditLogCleared = SecurityEvent
| where TimeGenerated > ago(24h)
| where EventID in (1102, 104)
| project Timestamp=TimeGenerated, DeviceName=Computer,
AccountName=strcat(SubjectDomainName, "\\", SubjectUserName),
ProcessName="wevtutil.exe / Windows Event Log",
CommandLine="N/A",
FilePath=iff(EventID == 1102, "Windows Security Event Log", "Windows System Event Log"),
Alert="AuditLogCleared",
AlertSeverity="Critical";
// Branch 2: Database file modified or created by scripting interpreter
let DatabaseTampering = DeviceFileEvents
| where Timestamp > ago(24h)
| where ActionType in ("FileModified", "FileCreated", "FileRenamed")
| extend FileExt = tolower(tostring(split(FileName, ".")[-1]))
| where FileExt in (DatabaseExtensions)
| where InitiatingProcessFileName has_any (ScriptingEngines)
| project Timestamp, DeviceName, AccountName=InitiatingProcessAccountName,
ProcessName=InitiatingProcessFileName,
CommandLine=InitiatingProcessCommandLine,
FilePath=strcat(FolderPath, "\\", FileName),
Alert="DatabaseFileTampering",
AlertSeverity="High";
// Branch 3: Bulk file modification burst — single process modifies 80+ files across 3+ folders in 5 min
let BulkModification = DeviceFileEvents
| where Timestamp > ago(2h)
| where ActionType in ("FileModified", "FileCreated", "FileRenamed", "FileDeleted")
| summarize FileCount=count(),
FolderCount=dcount(FolderPath),
SampleFiles=make_set(FileName, 5),
CommandLine=any(InitiatingProcessCommandLine)
by DeviceName,
InitiatingProcessFileName,
InitiatingProcessAccountName,
TimeBin=bin(Timestamp, 5m)
| where FileCount > 80 and FolderCount >= 3
| project Timestamp=TimeBin, DeviceName,
AccountName=InitiatingProcessAccountName,
ProcessName=InitiatingProcessFileName,
CommandLine,
FilePath=strcat("BulkOp (", tostring(FileCount), " files): ", tostring(SampleFiles)),
Alert="BulkFileModification",
AlertSeverity="Medium";
// Branch 4: Critical system/log path file modification by unexpected process
let CriticalPathTampering = DeviceFileEvents
| where Timestamp > ago(24h)
| where ActionType in ("FileModified", "FileDeleted", "FileRenamed")
| where FolderPath has_any (CriticalLogPaths)
| where InitiatingProcessFileName !in~ (LegitFileActors)
| project Timestamp, DeviceName, AccountName=InitiatingProcessAccountName,
ProcessName=InitiatingProcessFileName,
CommandLine=InitiatingProcessCommandLine,
FilePath=strcat(FolderPath, "\\", FileName),
Alert="CriticalPathTampering",
AlertSeverity="High";
// Union all branches into single alert stream
union AuditLogCleared, DatabaseTampering, BulkModification, CriticalPathTampering
| project Timestamp, DeviceName, AccountName, ProcessName, CommandLine,
Alert, AlertSeverity, FilePath
| sort by Timestamp desc Detects data manipulation activity using four detection branches unified into a single alert stream. Branch 1 catches Windows Security (Event ID 1102) and System (Event ID 104) event log clearing — a critical indicator of adversary evidence destruction. Branch 2 identifies database files (.mdf, .ldf, .db, .sqlite, .accdb, and others) being created or modified by scripting engines (PowerShell, Python, wscript, etc.), suggesting automated record injection or corruption. Branch 3 flags bulk file modification bursts where a single process modifies more than 80 files across 3+ distinct folders within a 5-minute window, consistent with automated data falsification or ransomware-like tampering. Branch 4 detects non-standard processes modifying files in critical system paths (Windows event log directories, IIS logs, SQL Server data directories, Windows\System32\config). Queries DeviceFileEvents from Microsoft Defender for Endpoint and SecurityEvent from Windows Security logs.
Data Sources
Required Tables
False Positives
- Backup software (Veeam, Commvault, Windows Server Backup, rsync) performing legitimate bulk file copies, database snapshots, or .bak file creation during scheduled backup windows
- Database maintenance jobs — SQL Server maintenance plans, DBCC CHECKDB, SQLite VACUUM, or MySQL/PostgreSQL dump operations — that routinely create and modify .mdf, .ldf, .db, or .bak files
- Software deployment and patch management systems (SCCM, Intune, Ansible, Chef) using PowerShell or cmd.exe to update configuration files, application databases, or perform bulk file operations during maintenance windows
- Log aggregation and SIEM forwarding agents that archive, compress, or clear old Windows event logs as part of scheduled log rotation or log shipping workflows
- CI/CD pipeline agents executing database schema migrations, bulk data seeding, or file generation steps via scripting engines during deployment runs
Sigma rule & cross-platform mapping
The detection logic for Data Manipulation (T1565) above is provided in a vendor-neutral
form so you can deploy it on any SIEM. The same logic is shipped here as native
KQL (Microsoft Sentinel / Defender), SPL (Splunk), Elastic (Elastic Security (EQL)), QRadar (IBM QRadar (AQL)), Sumo (Sumo Logic CSE), YARA-L (Google Chronicle / SecOps), LogScale (CrowdStrike LogScale (CQL)) queries. In Sigma terms, this detection targets the
following logsource:
logsource:
product: windows Browse the community-maintained Sigma rules for this technique:
Platform-specific guides for T1565
References (11)
- https://attack.mitre.org/techniques/T1565/
- https://attack.mitre.org/techniques/T1565/001/
- https://attack.mitre.org/techniques/T1565/002/
- https://attack.mitre.org/techniques/T1565/003/
- https://f.hubspotusercontent30.net/hubfs/8776530/Sygnia-%20Elephant%20Beetle_Jan2022.pdf
- https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/advanced-hunting-devicefileevents-table
- https://learn.microsoft.com/en-us/windows/security/threat-protection/auditing/event-1102
- https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon
- https://github.com/SigmaHQ/sigma/tree/master/rules/windows/file
- https://www.cisa.gov/sites/default/files/2024-01/CISA_Techniques_for_Detecting_Data_Tampering.pdf
- https://www.mandiant.com/resources/blog/fin13-elephant-beetle-targeted-financial-frauds
Testing Methodology
Validate this detection against 4 adversary techniques from Atomic Red Team. Each test below lists the behaviour to exercise and the telemetry you should expect to see. Executable commands and cleanup steps are available with Pro.
- Test 1Clear Windows Security Event Log
Expected signal: Security Event ID 1102 logged in the Security log immediately before clearing, capturing SubjectUserName and SubjectDomainName of the clearing account. Sysmon Event ID 1 (Process Create) showing wevtutil.exe execution with CommandLine 'cl Security'. Note: the Security log itself will be empty after execution — collect artifacts from SIEM/forwarded logs.
- Test 2Inject Fraudulent Record into SQLite Database via Python
Expected signal: Sysmon Event ID 1: Process Create with Image=python.exe, CommandLine containing sqlite3 and INSERT. Sysmon Event ID 11: FileCreate event for test_ledger.db in %TEMP% with python.exe as the initiating process. DeviceFileEvents: ActionType=FileCreated or FileModified, FileName=test_ledger.db, InitiatingProcessFileName=python.exe.
- Test 3Bulk File Content Modification Simulating Data Falsification
Expected signal: Multiple Sysmon Event ID 11 (FileCreate) events in rapid succession with powershell.exe as the initiating process, spanning 4 different subdirectories. DeviceFileEvents will show 100+ FileModified/FileCreated events from powershell.exe across 4+ distinct FolderPath values within a 5-minute window.
- Test 4Tamper with IIS/Web Application Log File via PowerShell
Expected signal: Sysmon Event ID 11: FileCreate with TargetFilename matching u_ex260318.log, Image=powershell.exe. DeviceFileEvents: ActionType=FileCreated or FileModified, FileName containing IIS log naming convention, InitiatingProcessFileName=powershell.exe. The file path does not match the real IIS log directory but demonstrates the process-level signal.
Response Playbook
Triage
- Identify what data was modified: retrieve the exact file path, size change, and SHA256 hash before and after modification from DeviceFileEvents or Sysmon Event ID 11. Compare against known-good hash from baseline or file integrity monitoring system.
- Examine the initiating process chain: what spawned the modifying process? Check InitiatingProcessParentFileName in DeviceFileEvents or ParentImage in Sysmon Event ID 1. If the chain is Office app → cmd.exe → python.exe → db file write, treat as high-confidence compromise.
- Determine the sensitivity of the modified data: is the affected file a financial ledger, security log, authentication database (SAM, NTDS.dit), application config, or operational data? Higher sensitivity raises priority to critical.
- For audit log clearing (Event ID 1102): check which account cleared the log and whether a corresponding change ticket exists. Determine the time window of log loss — what activity is now unrecoverable? Cross-reference with other log sources (Syslog, firewall, SIEM) to reconstruct the gap.
- For database file tampering: connect to the database (if accessible) and run integrity checks — DBCC CHECKDB for SQL Server, PRAGMA integrity_check for SQLite. Query recent transactions or changes to determine what records were added, modified, or deleted.
- Review the full command line of the modifying process for indicators of data manipulation intent: look for SQL injection strings, sed/awk/python one-liners with substitution patterns, hex editors run non-interactively, or scripts referencing financial record tables or log paths.
- Check for concurrent lateral movement indicators: were other hosts also affected? Did the same account or process hash appear on multiple systems near the same time? Use DeviceNetworkEvents or Sysmon Event ID 3 to check outbound connections from the modifying process.
Containment
- If active manipulation is in progress: immediately isolate the affected host using EDR network isolation or VLAN quarantine to prevent further changes and stop potential data exfiltration of manipulated records.
- Preserve the current state before remediation: take a forensic image or snapshot of affected file systems and database files. Do not run antivirus or cleanup tools that might overwrite artifacts. For VMs, suspend and snapshot before isolation.
- If the manipulating account is a service account or domain account: disable the account in Active Directory immediately, revoke all active tokens and Kerberos tickets (run klist purge on the affected host and force a password reset), and audit what other systems the account accessed.
- If audit logs were cleared: immediately enable enhanced auditing on the affected system and all peer systems in the same network segment. Alert the security team that the forensic timeline has a gap and document the start/end time of the gap precisely.
- For database tampering with financial or operational impact: engage the data owner and application team to assess business impact. Determine whether a clean backup restore is feasible or whether a transaction-level rollback is required. Do not restore blindly — ensure the backup predates the compromise.
- Block the identified C2 or staging infrastructure at the network perimeter (firewall, proxy, DNS) if the manipulation script downloaded its payload or exfiltrated results to an external IP.
Evidence Collection
- File Integrity: Sysmon Event ID 11 (TargetFilename, Image, ProcessId, SHA256) from the Microsoft-Windows-Sysmon/Operational log — captures file creation/modification events with process context.
- Process Context: Sysmon Event ID 1 (Process Create) and Security Event ID 4688 (with command line auditing enabled) — captures the full command line of the manipulating process and its parent.
- Database Transaction Logs: SQL Server transaction log (.ldf), MySQL binlog, PostgreSQL WAL, or SQLite WAL file — may contain a record of injected or altered transactions. Preserve before any DBCC or repair operations.
- Volume Shadow Copies: Check for existing VSS snapshots (vssadmin list shadows) that predate the manipulation — may allow recovery of original file state for comparison.
- Windows Event Logs: Security Event ID 1102 (audit log cleared), System Event ID 104 (system log cleared), Security Event ID 4719 (audit policy changed). All from Windows Event Logs — export before any clearing.
- File System Metadata: NTFS $MFT and $LogFile entries for the affected files — use tools like MFTECmd or FTK Imager to extract creation, modification, and last-accessed timestamps. MFT sequence numbers reveal modification count.
- PowerShell ScriptBlock Logs: Event ID 4104 from Microsoft-Windows-PowerShell/Operational — if PowerShell was the manipulation vector, captures the full deobfuscated script content.
- Network Captures: If transmitted data manipulation (T1565.002) is suspected, capture pcap from affected network segment using span port or in-line tap. Look for HTTP/database protocol manipulation, unexpected TLS certificate chains, or ARP spoofing artifacts.
- Prefetch Files: C:\Windows\Prefetch\ entries for the manipulating executable — contain execution timestamp and list of files accessed, useful for establishing timeline.
Escalation Criteria
- ! Financial or transactional data affected: any modification to payment records, accounting databases, ledgers, or billing systems requires immediate escalation to CISO and legal/compliance — potential regulatory notification obligation.
- ! Audit log cleared coinciding with other suspicious activity: log clearing following lateral movement, privilege escalation, or data access is a strong indicator of a deliberate cover-up, not accidental. Escalate to IR team immediately.
- ! NTDS.dit, SAM, or other credential database modified: any write to Active Directory database files, local SAM hive, or LSASS memory regions indicates credential harvesting infrastructure and requires emergency response.
- ! Multiple systems affected simultaneously: same pattern appearing across 3+ endpoints or servers within a short window suggests automated propagation or a coordinated multi-host manipulation campaign.
- ! Evidence of FIN13/similar financial fraud TTPs: repeated small-value transaction injections, fraudulent record insertion mimicking normal business activity, or manipulation of approval thresholds/control limits.
- ! Manipulation script or binary exhibits obfuscation, packing, or anti-analysis features: suggests nation-state or sophisticated criminal actor rather than insider threat or opportunistic attack.
Investigation Guide
Forensic Artifacts
- >
NTFS $MFT (Master File Table): Contains modification count, creation/modification/access timestamps, and file size history for every file. Accessible via FTK Imager or MFTECmd. Look for files with high modification counts or timestamps inconsistent with normal business hours. - >
NTFS $LogFile and $UsnJrnl: USN Journal records every file system operation including create, modify, rename, and delete with timestamps. Use fsutil usn readjournal or forensic tools to enumerate all changes in a time window. Critical for reconstructing exactly what was changed. - >
Windows Event Log: Security Event ID 1102 (Security log cleared), System Event ID 104 (System log cleared), Security Event ID 4719 (audit policy changed), Event ID 4907 (auditing settings changed on object). Located at C:\Windows\System32\winevt\Logs\. - >
Database Transaction Logs: SQL Server .ldf files, MySQL binary logs at /var/lib/mysql/mysql-bin.*, PostgreSQL WAL at pg_wal/, SQLite WAL at <database>.db-wal — all contain a sequential record of every committed transaction. Preserve before any repair operation. - >
Volume Shadow Copy Service snapshots: vssadmin list shadows — may contain pre-manipulation versions of affected files. Access via mklink /d C:\shadow \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy<N>\. - >
PowerShell PSReadLine History: %APPDATA%\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt — contains command history of interactive PowerShell sessions used for manipulation. - >
Python/scripting engine temp files and .pyc cache: Manipulation scripts may leave compiled .pyc files in __pycache__ directories or temp files in %TEMP% / /tmp. - >
Scheduled Task XML definitions: C:\Windows\System32\Tasks\ — if manipulation was scheduled for persistence, task XML files contain the command line and trigger configuration. Also check HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks. - >
Registry RunMRU and UserAssist keys: HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU and UserAssist — record recently executed commands and applications that may have been used for manual manipulation.
Tuning Guidance
Data manipulation is inherently high-noise because many legitimate processes perform bulk file I/O and database operations. Start tuning by building an inventory of scheduled jobs that perform large write operations (backup agents, ETL processes, database maintenance) and create allowlist conditions scoped to their specific service account + parent process + time window combinations. For the bulk modification threshold (80 files / 5 min), baseline your environment by running the hunting query over 30 days and identify the p95 and p99 write rates per process — set the threshold above the p99 to reduce false positives while still catching genuine manipulation bursts. For database file tampering, the most reliable signal is the combination of a database extension AND a scripting engine — narrow this further by excluding known-good scripting engine instances (e.g., SCCM's PowerShell invocations always originate from CcmExec.exe as grandparent). For audit log clearing (Event ID 1102), this is near-zero false-positive in most environments — the only common benign cause is manual log clearing by administrators or automated SIEM forwarder cleanup, both of which can be allowlisted by account name and time window. Enable File Integrity Monitoring (Windows: configure Audit File System in Advanced Audit Policy; Linux: auditd with -w watch rules on /etc/, /var/log/, and application data directories) to get more granular telemetry. Consider enriching alerts with asset classification — database file modification on a server tagged as 'financial-system' or 'PCI-scope' should auto-escalate to High regardless of the process involved.
Hunting Queries
Hunts for service accounts performing file writes to data-bearing file types (databases, CSVs, logs, XMLs) outside business hours (before 6am or after 10pm). Legitimate maintenance jobs typically run at known scheduled times — unexpected off-hours activity by service accounts writing to data paths is a strong indicator of adversary-controlled automation. High off-hours percentage or high write volume across many paths warrants investigation.
// Hunt: Service accounts writing to business data paths outside expected maintenance windows
// Flags: service account + business-hours exclusion + write to data-bearing paths
DeviceFileEvents
| where Timestamp > ago(7d)
| where ActionType in ("FileModified", "FileCreated", "FileRenamed")
| where InitiatingProcessAccountName startswith "svc-"
or InitiatingProcessAccountName endswith "_svc"
or InitiatingProcessAccountName endswith "$"
| extend FileExt = tolower(tostring(split(FileName, ".")[-1]))
| where FileExt in ("db", "sqlite", "mdb", "accdb", "csv", "json", "xml", "txt", "log", "bak")
| extend HourOfDay = datetime_part("Hour", Timestamp)
| extend IsOffHours = iff(HourOfDay < 6 or HourOfDay > 22, true, false)
| summarize TotalWrites=count(), OffHoursWrites=countif(IsOffHours == true),
UniquePaths=dcount(FolderPath), SampleFiles=make_set(FileName, 5)
by DeviceName, InitiatingProcessAccountName, InitiatingProcessFileName
| where OffHoursWrites > 10 or (TotalWrites > 50 and UniquePaths > 5)
| extend OffHoursPct = round(100.0 * OffHoursWrites / TotalWrites, 1)
| sort by OffHoursWrites desc index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=11
| eval FileExt=lower(mvindex(split(TargetFilename, "."), -1))
| where match(FileExt, "^(db|sqlite|mdb|accdb|csv|json|xml|txt|log|bak)$")
| eval IsServiceAccount=if(match(lower(User), "(svc[-_]|_svc$|\\$$)"), 1, 0)
| where IsServiceAccount=1
| eval HourOfDay=tonumber(strftime("%H", _time))
| eval IsOffHours=if(HourOfDay < 6 OR HourOfDay > 22, 1, 0)
| stats count as TotalWrites, sum(IsOffHours) as OffHoursWrites,
dc(TargetFilename) as UniquePaths,
values(eval(mvindex(split(TargetFilename, "\\"), -1))) as SampleFiles
by host, User, Image
| where OffHoursWrites > 10 OR (TotalWrites > 50 AND UniquePaths > 5)
| eval OffHoursPct=round(OffHoursWrites/TotalWrites*100, 1)
| sort - OffHoursWrites Hunts for processes writing to web server and web application directories that are not the expected web server process. Legitimate writes to web roots come from w3wp.exe, httpd, nginx, node, or deployment/installer processes. Unexpected writers — especially scripting engines or unknown binaries — may indicate web shell deployment, config tampering, or content defacement as part of a broader data manipulation campaign.
// Hunt: Processes accessing web application log and config paths they do not normally touch
// Surfaces unexpected writers to web server and application config paths
let WebPaths = dynamic([
"\\inetpub\\", "\\apache\\", "\\nginx\\", "\\tomcat\\",
"\\www\\", "\\htdocs\\", "\\webroot\\"
]);
let ExpectedWebProcesses = dynamic([
"w3wp.exe", "httpd.exe", "nginx.exe", "java.exe", "tomcat.exe",
"node.exe", "dotnet.exe", "php-cgi.exe", "WMSvc.exe"
]);
DeviceFileEvents
| where Timestamp > ago(7d)
| where ActionType in ("FileModified", "FileCreated", "FileRenamed")
| where FolderPath has_any (WebPaths)
| where InitiatingProcessFileName !in~ (ExpectedWebProcesses)
| where InitiatingProcessFileName !in~ ("TrustedInstaller.exe", "msiexec.exe", "wuauclt.exe")
| summarize WriteCount=count(), ModifiedFiles=make_set(strcat(FolderPath, "\\", FileName), 10)
by DeviceName, InitiatingProcessFileName, InitiatingProcessAccountName,
InitiatingProcessCommandLine
| sort by WriteCount desc index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=11
| where match(lower(TargetFilename), "(\\\\inetpub\\\\|\\\\apache\\\\|\\\\nginx\\\\|\\\\tomcat\\\\|\\\\www\\\\|\\\\webroot\\\\)")
| where NOT match(lower(Image), "(w3wp\.exe|httpd\.exe|nginx\.exe|java\.exe|tomcat\.exe|node\.exe|dotnet\.exe|php-cgi\.exe|trustedinstaller\.exe|msiexec\.exe)")
| stats count as WriteCount, values(TargetFilename) as ModifiedFiles
by host, User, Image, CommandLine
| sort - WriteCount Hunts for executable, script, and configuration files that were deleted and recreated with a different hash within a 60-minute window — the classic file replacement pattern used to swap legitimate binaries or configs with malicious versions. This differs from the main detection by focusing on hash-change evidence rather than process behavior, making it effective for detecting manipulation that uses 'legitimate' system tools or occurred via direct disk access bypassing process instrumentation.
// Hunt: Detect file hash changes on sensitive files by comparing creation events against known baseline
// Surfaces files that were recreated (delete + recreate pattern used to replace content)
DeviceFileEvents
| where Timestamp > ago(7d)
| where ActionType in ("FileDeleted", "FileCreated")
| extend FileExt = tolower(tostring(split(FileName, ".")[-1]))
| where FileExt in ("exe", "dll", "bat", "ps1", "vbs", "js", "py", "conf", "config", "ini", "xml", "json")
| summarize Actions=make_set(ActionType), Hashes=make_set(SHA256),
FirstSeen=min(Timestamp), LastSeen=max(Timestamp),
EventCount=count()
by DeviceName, FolderPath, FileName
| where Actions has "FileDeleted" and Actions has "FileCreated"
| where array_length(Hashes) > 1
| extend TimeDeltaMinutes = datetime_diff("minute", LastSeen, FirstSeen)
| where TimeDeltaMinutes < 60
| sort by TimeDeltaMinutes asc index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=11 earliest=-7d
| eval FileExt=lower(mvindex(split(TargetFilename, "."), -1))
| where match(FileExt, "^(exe|dll|bat|ps1|vbs|js|py|conf|config|ini|xml|json)$")
| eval FilePath=lower(TargetFilename)
| stats values(Hashes) as SeenHashes, values(EventCode) as EventCodes,
earliest(_time) as FirstSeen, latest(_time) as LastSeen, count as EventCount
by host, FilePath
| eval TimeDeltaMins=round((LastSeen - FirstSeen)/60, 1)
| where EventCount >= 2 AND mvcount(SeenHashes) > 1 AND TimeDeltaMins < 60
| sort TimeDeltaMins Atomic Red Team Tests
Clears the Windows Security event log using wevtutil, the built-in Windows event log management tool. This simulates adversary evidence destruction after a compromise — a critical step in hiding manipulation activity and eliminating forensic evidence. Generates Security Event ID 1102 immediately before the log is cleared, providing a detectable artifact.
Command
wevtutil.exe cl Security Expected Telemetry
Security Event ID 1102 logged in the Security log immediately before clearing, capturing SubjectUserName and SubjectDomainName of the clearing account. Sysmon Event ID 1 (Process Create) showing wevtutil.exe execution with CommandLine 'cl Security'. Note: the Security log itself will be empty after execution — collect artifacts from SIEM/forwarded logs.
Expected Detection
Alert fires on Branch 1 (AuditLogCleared) in KQL via SecurityEvent where EventID == 1102. SPL: AlertType='AuditLogCleared', AlertSeverity='Critical'. This is a near-zero false-positive detection in most environments.
Simulates the FIN13 pattern of fraudulent transaction injection by using Python to open a SQLite database and insert a falsified record. Demonstrates how scripting engines can be used for stored data manipulation (T1565.001) against local database files. The database and table are created fresh for the test to avoid affecting real data.
Command
python.exe -c "import sqlite3, os; db=os.path.join(os.environ['TEMP'],'test_ledger.db'); conn=sqlite3.connect(db); conn.execute('CREATE TABLE IF NOT EXISTS transactions (id INTEGER PRIMARY KEY, amount REAL, status TEXT, modified_by TEXT)'); conn.execute(\"INSERT INTO transactions (amount, status, modified_by) VALUES (99999.99, 'approved', 'adversary')\"); conn.commit(); conn.close(); print('Record injected into ' + db)" Cleanup
python.exe -c "import os; os.remove(os.path.join(os.environ['TEMP'],'test_ledger.db'))" Expected Telemetry
Sysmon Event ID 1: Process Create with Image=python.exe, CommandLine containing sqlite3 and INSERT. Sysmon Event ID 11: FileCreate event for test_ledger.db in %TEMP% with python.exe as the initiating process. DeviceFileEvents: ActionType=FileCreated or FileModified, FileName=test_ledger.db, InitiatingProcessFileName=python.exe.
Expected Detection
Alert fires on Branch 2 (DatabaseFileTampering) — FileExt 'db' is in DatabaseExtensions, and python.exe is in ScriptingEngines. KQL: Alert='DatabaseFileTampering', AlertSeverity='High'. SPL: AlertType='DatabaseFileTampering', IsDbFile=1, IsScriptingEngine=1.
Creates 100 data files and then overwrites all of them with falsified content using PowerShell, simulating an adversary script that bulk-modifies financial records, operational data, or log entries. The rapid modification of many files across multiple directories within a short window is the primary detection signal for automated data manipulation campaigns.
Command
powershell.exe -NoProfile -Command "$base = '$env:TEMP\datamanip_test'; @('set1','set2','set3','set4') | ForEach-Object { $dir = \"$base\\$_\"; New-Item -ItemType Directory -Path $dir -Force | Out-Null; 1..25 | ForEach-Object { Set-Content -Path \"$dir\\record_$_.csv\" -Value \"id,amount,status`n$_,$(Get-Random -Max 9999),original\" } }; Write-Host 'Created baseline files'; Start-Sleep -Seconds 2; @('set1','set2','set3','set4') | ForEach-Object { $dir = \"$base\\$_\"; Get-ChildItem $dir -Filter '*.csv' | ForEach-Object { Set-Content -Path $_.FullName -Value \"id,amount,status`n$(Get-Random),99999,FALSIFIED\" } }; Write-Host 'Bulk modification complete'" Cleanup
powershell.exe -NoProfile -Command "Remove-Item -Recurse -Force '$env:TEMP\datamanip_test' -ErrorAction SilentlyContinue" Expected Telemetry
Multiple Sysmon Event ID 11 (FileCreate) events in rapid succession with powershell.exe as the initiating process, spanning 4 different subdirectories. DeviceFileEvents will show 100+ FileModified/FileCreated events from powershell.exe across 4+ distinct FolderPath values within a 5-minute window.
Expected Detection
Alert fires on Branch 3 (BulkFileModification) — FileCount > 80 and FolderCount >= 3 within 5-minute bin. KQL: Alert='BulkFileModification', AlertSeverity='Medium'. SPL: appendcols subsearch detects FileCount > 80 AND UniqueFolders >= 3. Analyst should pivot to the CommandLine to confirm malicious intent.
Appends a falsified log entry to an IIS-format log file using PowerShell, simulating an adversary modifying web server access logs to hide malicious HTTP requests or insert false records that mislead forensic investigation. Targets a temporary file mimicking an IIS log path to avoid affecting real web logs.
Command
powershell.exe -NoProfile -Command "$logPath = '$env:TEMP\u_ex260318.log'; if (-not (Test-Path $logPath)) { Set-Content $logPath '#Software: Microsoft Internet Information Services 10.0`n#Version: 1.0`n#Date: 2026-03-18 00:00:00`n#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status' }; Add-Content $logPath '2026-03-18 03:14:15 192.168.1.1 GET /admin/config.php - 443 - 10.0.0.99 Mozilla/5.0 200'" Cleanup
Remove-Item '$env:TEMP\u_ex260318.log' -ErrorAction SilentlyContinue Expected Telemetry
Sysmon Event ID 11: FileCreate with TargetFilename matching u_ex260318.log, Image=powershell.exe. DeviceFileEvents: ActionType=FileCreated or FileModified, FileName containing IIS log naming convention, InitiatingProcessFileName=powershell.exe. The file path does not match the real IIS log directory but demonstrates the process-level signal.
Expected Detection
Alert fires on Branch 4 (CriticalPathTampering) if the file were in a monitored path, or on Branch 2 if the extension matched database types. In this test, Sysmon Event ID 11 is generated and visible in the hunting query for unexpected web path writers if deployed under an IIS-monitored directory. Adjust the path to C:\inetpub\logs\LogFiles\W3SVC1\ for full detection coverage in environments with IIS.