Scheduled Task/Job
Adversaries may abuse task scheduling functionality to facilitate initial or recurring execution of malicious code. Utilities exist within all major operating systems to schedule programs or scripts to be executed at a specified date and time. A task can also be scheduled on a remote system, provided the proper authentication is met (ex: RPC and file and printer sharing in Windows environments). Adversaries use task scheduling to execute programs at system startup or on a scheduled basis for persistence, to run processes under elevated account contexts (such as SYSTEM), and to potentially mask one-time execution under a trusted system process. Sub-techniques cover Windows Task Scheduler (T1053.005), the legacy AT command (T1053.002), Unix cron (T1053.003), Linux systemd timers (T1053.006), and container orchestration jobs (T1053.007).
What is T1053 Scheduled Task/Job?
Scheduled Task/Job (T1053) maps to the Execution and Persistence and Privilege Escalation tactics — the adversary is trying to run malicious code in MITRE ATT&CK.
This page provides production-ready detection logic for Scheduled Task/Job, covering the data sources and telemetry it touches: Process: Process Creation, Scheduled Job: Scheduled Job Creation, Command: Command Execution, Microsoft Defender for Endpoint, Windows Security Event Log. 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
- Technique
- T1053 Scheduled Task/Job
- Canonical reference
- https://attack.mitre.org/techniques/T1053/
// T1053 — Scheduled Task/Job: Multi-branch Windows detection
// Branch 1: schtasks.exe / at.exe process creation with suspicious indicators
let SuspiciousTaskCreation = DeviceProcessEvents
| where Timestamp > ago(24h)
| where FileName in~ ("schtasks.exe", "at.exe")
| where ProcessCommandLine has_any ("/create", "/change", "-create", "-change")
| extend RunAsSystem = ProcessCommandLine has_any ("/ru SYSTEM", "/ru \"NT AUTHORITY\\SYSTEM\"")
| extend SuspiciousPath = ProcessCommandLine has_any (
"%APPDATA%", "%TEMP%", "%PUBLIC%",
"\\AppData\\Local\\Temp", "\\AppData\\Roaming\\",
"C:\\Users\\Public\\", "C:\\ProgramData\\", "C:\\Windows\\Temp\\"
)
| extend RemoteTask = ProcessCommandLine has "/s "
| extend ScriptExecution = ProcessCommandLine has_any (
"powershell", "wscript", "cscript", "mshta",
"regsvr32", "rundll32", "cmd /c", "cmd.exe /c", "certutil"
)
| extend HiddenFlag = ProcessCommandLine has " /f"
| where RunAsSystem or SuspiciousPath or RemoteTask or ScriptExecution
| extend SuspicionScore = (toint(RunAsSystem) + toint(SuspiciousPath) + toint(RemoteTask) + toint(ScriptExecution))
| project
Timestamp, DeviceName, AccountName,
FileName, ProcessCommandLine,
InitiatingProcessFileName, InitiatingProcessCommandLine,
RunAsSystem, SuspiciousPath, RemoteTask, ScriptExecution, HiddenFlag, SuspicionScore,
DetectionBranch = "schtasks_process_creation";
// Branch 2: Security Event 4698 — Scheduled Task Created (audit log)
let TaskAuditEvents = SecurityEvent
| where TimeGenerated > ago(24h)
| where EventID == 4698
| extend TaskName = extract(@"<TaskName>(.*?)</TaskName>", 1, EventData)
| extend TaskAction = extract(@"<Command>(.*?)</Command>", 1, EventData)
| extend TaskArguments = extract(@"<Arguments>(.*?)</Arguments>", 1, EventData)
| extend TaskPrincipal = extract(@"<UserId>(.*?)</UserId>", 1, EventData)
| extend RunAsSystem = TaskPrincipal has_any ("SYSTEM", "S-1-5-18")
| extend SuspiciousAction = (TaskAction has_any (
"powershell", "wscript", "cscript", "mshta", "regsvr32",
"rundll32", "cmd.exe", "certutil"
) or TaskArguments has_any (
"AppData", "\\Temp\\", "\\Public\\", "ProgramData", "http", "EncodedCommand", "-enc"
))
| where SuspiciousAction
| extend SuspicionScore = toint(SuspiciousAction) + toint(RunAsSystem)
| project
TimeGenerated, Computer, Account,
TaskName, TaskAction, TaskArguments, TaskPrincipal,
RunAsSystem, SuspiciousAction, SuspicionScore,
DetectionBranch = "security_event_4698";
// Union both branches and sort
union SuspiciousTaskCreation, TaskAuditEvents
| sort by coalesce(Timestamp, TimeGenerated) desc Multi-branch detection for T1053 Scheduled Task/Job abuse on Windows using Microsoft Defender for Endpoint and Windows Security event logs. Branch 1 monitors DeviceProcessEvents for schtasks.exe and at.exe invocations with suspicious parameters: SYSTEM execution context, writable/temporary directory paths, remote task creation (/s flag), and scripting engine invocations (PowerShell, wscript, mshta, regsvr32, rundll32). Branch 2 parses Security Event 4698 (task created) to extract task action and principal, alerting when the task action contains known scripting engines or suspicious path patterns in arguments. A SuspicionScore field aggregates multiple indicators to aid analyst triage and prioritization.
Data Sources
Required Tables
False Positives
- IT automation and configuration management tools (SCCM/CCMExec, Intune, Ansible WinRM) creating scheduled tasks for software deployment, patching, and policy enforcement — typically identifiable by ccmexec.exe or msiexec.exe as the initiating process
- Monitoring and observability agents (Datadog, SolarWinds, Nagios, Elastic Agent) scheduling periodic data collection or health check tasks with actions in ProgramData or similar directories
- Legitimate software products creating update or maintenance tasks at installation time (Adobe, Chrome, Java, antivirus products) — usually run from %APPDATA% or ProgramData with predictable task names and vendor-signed binaries
- System administrators creating administrative maintenance scripts scheduled as SYSTEM for disk cleanup, log archival, certificate renewal, or backup operations
- Development and CI/CD pipelines on build agents creating tasks as part of automated test execution or environment setup, often with PowerShell actions in Temp directories
Sigma rule & cross-platform mapping
The detection logic for Scheduled Task/Job (T1053) 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:
category: process_creation
product: windows Browse the community-maintained Sigma rules for this technique:
Platform-specific guides for T1053
References (11)
- https://attack.mitre.org/techniques/T1053/
- https://docs.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page
- https://www.ultimatewindowssecurity.com/securitylog/encyclopedia/event.aspx?eventid=4698
- https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1053/T1053.md
- https://github.com/SigmaHQ/sigma/tree/master/rules/windows/builtin/taskscheduler
- https://www.proofpoint.com/us/blog/threat-insight/serpent-no-swiping-new-backdoor-targets-french-entities-unique-attack-chain
- https://thedfirreport.com/2021/10/18/icedid-to-xinglocker-ransomware-in-24-hours/
- https://research.nccgroup.com/2021/01/12/abusing-task-scheduler-for-persistence/
- https://docs.microsoft.com/en-us/sysinternals/downloads/autoruns
- https://www.mandiant.com/resources/blog/apt41-us-state-governments
- https://technet.microsoft.com/en-us/library/cc785125.aspx
Testing Methodology
Validate this detection against 5 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 1Create Scheduled Task Running as SYSTEM at Startup
Expected signal: Sysmon Event ID 1: schtasks.exe with CommandLine containing '/create', '/ru SYSTEM', '/sc onstart', and '/f'. Security Event ID 4698 in Windows Security log with TaskName=\Microsoft\Windows\df00tech-test and TaskPrincipal referencing SYSTEM (S-1-5-18). TaskScheduler Operational Event ID 106 (task registered). Task XML created at C:\Windows\System32\Tasks\Microsoft\Windows\df00tech-test.
- Test 2Scheduled Task with PowerShell Encoded Command Payload
Expected signal: Sysmon Event ID 1: powershell.exe executing Register-ScheduledTask via ScheduledTasks module. Security Event ID 4698 with TaskName=df00tech-encoded-test and Action Command=powershell.exe with '-EncodedCommand' in Arguments. TaskScheduler Operational Event ID 106. Task XML in C:\Windows\System32\Tasks\df00tech-encoded-test with Hidden=true and encoded argument visible in task XML.
- Test 3Remote Scheduled Task Creation via schtasks /s
Expected signal: Sysmon Event ID 1: schtasks.exe with CommandLine containing '/s 127.0.0.1' and '/create'. Sysmon Event ID 3: outbound network connection to 127.0.0.1 on port 445 (SMB) or 135 (RPC/DCOM) for remote task registration. Security Event ID 4648 (logon with explicit credentials) if /u and /p are provided. Security Event ID 4698 on the target for the new task.
- Test 4Linux Crontab Persistence — Download and Execute Pattern
Expected signal: Auditd: openat/write syscall to /var/spool/cron/crontabs/<username> or /tmp/crontab.XXXXXX (temp file used by crontab command). Process creation for 'crontab' binary with '-' as argument (reading from stdin). After 5 minutes: crond/cron spawns /bin/bash with the -c argument, creating /tmp/df00tech-cron-out.txt. Syslog shows cron job execution: 'CRON[PID]: (user) CMD (/bin/bash -c ...'.
- Test 5Scheduled Task via XML Import — Masquerading as Windows Component
Expected signal: Sysmon Event ID 1: schtasks.exe with CommandLine containing '/xml' and task name under \Microsoft\Windows\WindowsDefender\. Sysmon Event ID 11: XML file creation in %TEMP%. Security Event ID 4698 with full task XML in EventData — shows Hidden=true, 5-minute repeating trigger, and cmd.exe action. TaskScheduler Operational Event 106. Task XML persisted at C:\Windows\System32\Tasks\Microsoft\Windows\WindowsDefender\df00tech-DefenderUpdate.
Response Playbook
Triage
- Identify the task creation method: was it via schtasks.exe command line, direct XML import (schtasks /create /xml), PowerShell's Register-ScheduledTask, WMI Schedule.Service COM object, or direct registry manipulation under HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache? Each method leaves different forensic artifacts.
- Examine the task action fully: what executable or script does the task run? Decode any Base64-encoded arguments (e.g., PowerShell -EncodedCommand) using: [System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('<value>')). Check whether the action binary exists on disk and verify its digital signature.
- Review the task trigger type: OnBoot and OnLogon triggers indicate persistence intent. Recurring short-interval triggers (every 1-5 minutes) suggest beaconing or watchdog behavior for a running implant. One-time triggers may indicate a detonation mechanism.
- Identify the run-as principal: tasks running as SYSTEM (S-1-5-18), a service account, or an elevated user without a corresponding change ticket warrant escalation. Standard user tasks created by a standard user are lower-priority unless the action itself is suspicious.
- Determine the initiating process: what created this task? Legitimate origins include msiexec.exe (software installers), ccmexec.exe (SCCM), and known admin tools. Suspicious origins include Office applications (winword.exe, excel.exe), browser processes, script interpreters invoked via phishing, or unknown binaries from writable directories.
- Correlate with preceding events on the same host: did a download, suspicious process creation, or phishing-related activity occur in the 30 minutes before task creation? Scheduled tasks are typically the persistence step following initial code execution and should not appear in isolation on clean hosts.
- For remote task creation (/s flag in schtasks.exe): identify the target hostname or IP and the credentials used. Verify via Active Directory logs (Event 4648) whether those credentials were used on multiple hosts simultaneously — a lateral movement indicator.
Containment
- Delete the malicious scheduled task immediately: schtasks /delete /tn "<TaskName>" /f — then monitor for re-creation within 5 minutes using the Task Scheduler Operational log (Event 106). Re-creation indicates a live implant actively re-establishing persistence and requires process hunting before a second deletion attempt.
- If the task action has already executed, isolate the host from the network using EDR network isolation or VLAN quarantine before proceeding — lateral movement or C2 check-in may have already occurred.
- Kill any processes spawned by the scheduled task, recording PIDs, start times, and full command lines for forensic documentation before termination. Note any child processes that may have spawned additional implants.
- If the task ran under a specific user account or service account, disable that account in Active Directory immediately and revoke all active sessions and Kerberos tickets (use klist purge on the affected host). Reset the account password before re-enabling.
- Block execution of the malicious binary or script at the path specified in the task action using application control (WDAC, AppLocker, or Defender ASR rules). This prevents re-execution if the task is recreated by a persistence watchdog.
- For remote scheduled tasks: enumerate other hosts where the same credentials were used (correlate Security Event 4648 across SIEM) and initiate parallel containment on each affected host to prevent propagation.
Evidence Collection
- Windows Security Event Log: Event IDs 4698 (created), 4699 (deleted), 4700 (enabled), 4701 (disabled), 4702 (updated) — export the full log from the affected host before log rotation; these events require 'Audit Other Object Access Events' under Object Access audit policy to be enabled
- Microsoft-Windows-TaskScheduler/Operational log: Event IDs 106 (task registered), 129 (task process launched), 140 (task registration updated), 141 (task registration deleted), 200 (action started), 201 (action completed) — correlate with process execution timestamps for timeline reconstruction
- Task XML definition files: C:\Windows\System32\Tasks\ and C:\Windows\SysWOW64\Tasks\ — collect all XML files from the relevant directory; task XML contains the action, trigger, principal, creation metadata, and hash
- Registry: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\{GUID} and \Tree\ — binary task data persists here even after the XML file is deleted; export full hive for offline analysis
- Sysmon Event ID 1 logs for schtasks.exe execution and the spawned task process — capture process ancestry, command lines, file hashes, and parent context
- Sysmon Event ID 11 (file creation) for any binaries or scripts written to disk by the task or its parent process
- Sysmon Event ID 3 (network connection) for outbound connections made by the task's spawned process — critical for identifying C2 infrastructure
- Prefetch files: C:\Windows\Prefetch\ for the task's executable binary — provides execution timestamps and a list of DLLs loaded during execution
- PowerShell ScriptBlock Logging (Event ID 4104) if the task action involved PowerShell — captures full deobfuscated script content including decoded Base64 payloads
Escalation Criteria
- ! Task is configured to run as SYSTEM or a privileged service account with no corresponding software installation, maintenance window, or change request — SYSTEM-context tasks from unexpected parents are high-confidence malicious
- ! Task action executes a Base64-encoded PowerShell command, a binary from TEMP/AppData/Public/ProgramData, or makes an immediate outbound network connection after launch — indicates active implant deployment
- ! Task was created by an unexpected parent process (Office application, browser, script interpreter not launched by an admin) — indicates post-exploitation persistence following successful initial access
- ! Remote task creation detected (/s flag) — implies the attacker holds valid credentials and is conducting lateral movement to other hosts in the environment
- ! Identical or near-identical tasks appearing on multiple endpoints within a short time window — suggests automated deployment via compromised account, domain GPO abuse, or worm-like propagation
- ! Task deletion and re-creation observed within minutes of analyst containment — a live watchdog process is actively maintaining persistence and the primary implant has not been killed
- ! Task creation event coincides with other high-severity alerts on the same host or for the same account (credential dumping, defense evasion, C2 beaconing) within the same 30-minute window
Investigation Guide
Forensic Artifacts
- >
File System: C:\Windows\System32\Tasks\ — XML task definitions; filenames match task names; directory structure mirrors Task Scheduler tree hierarchy; survives most cleanup attempts unless explicitly deleted - >
File System: C:\Windows\SysWOW64\Tasks\ — 32-bit task definitions on 64-bit systems; some malware specifically targets this path to avoid detection tools that only monitor System32 - >
Registry: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks\{GUID} — binary-encoded task data including last run time, next run time, task hash, and status; GUID correlates to the task XML - >
Registry: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree\ — hierarchical structure mapping task names to GUIDs; persists even after XML deletion until TaskCache is flushed - >
Registry: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Boot\ and \Logon\ — tasks specifically triggered at boot or logon are enumerated here; check for unexpected entries - >
Event Log: Microsoft-Windows-TaskScheduler/Operational — complete task lifecycle including creation, modification, execution, and deletion with timestamps; located at Applications and Services Logs in Event Viewer - >
Event Log: Windows Security (EventIDs 4698-4702) — task creation/modification audit events; require Object Access auditing to be enabled via Group Policy - >
Linux: /var/spool/cron/crontabs/<username> — per-user crontab files; check modification timestamps with stat and compare to known baseline - >
Linux: /etc/cron.d/, /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/, /etc/cron.monthly/ — system-wide cron job directories; adversaries with root access may drop files here - >
macOS: ~/Library/LaunchAgents/, /Library/LaunchAgents/, /Library/LaunchDaemons/ — launchd plist files; compare against Apple-signed baseline; user-writable LaunchAgents persists across logouts - >
Prefetch: C:\Windows\Prefetch\ — execution evidence for the task binary even if the binary is later deleted; timestamps indicate when the task last ran
Tuning Guidance
The primary false positive source for T1053 detections is legitimate IT automation. The most effective tuning strategy is to build per-environment allowlists based on the initiating process + task action combination rather than task names alone (malware frequently masquerades as legitimate task names like Windows Defender or Windows Update). Start by collecting 7 days of Security Event 4698 data in observe-only mode and cluster by (Account, InitiatingProcessFileName, TaskAction) to identify the steady-state baseline for your environment. SCCM and Intune deployments are typically identifiable by ccmexec.exe or msiexec.exe as the parent process — add these as process-level exclusions, not name-level exclusions. For the process creation branch, consider requiring SuspicionScore >= 2 to reduce noise while maintaining coverage for high-confidence multi-indicator combinations. Enable Windows Security auditing for 'Audit Other Object Access Events' under the Object Access policy if Event 4698 is absent in your environment — it is not enabled by default but is essential for task audit coverage. For high-sensitivity assets (domain controllers, Exchange servers, PKI infrastructure), maintain a strict allowlist of expected task names and alert on ANY task not on the approved list regardless of action content. On Linux, deploy auditd rules to monitor writes to /var/spool/cron/, /etc/cron.d/, and /etc/cron.*/ directories: -w /var/spool/cron/ -p wa -k cron_modification. Integrate with a CMDB or asset inventory to suppress alerts from hosts that are known build agents or software deployment targets, which legitimately create and delete tasks frequently.
Hunting Queries
Hunt for schtasks.exe invoked from unexpected parent processes. Legitimate task creation originates from known sources: installers (msiexec), admin tools (PowerShell, cmd), or system components (svchost, services). Unexpected parents — Office applications, browser processes, script interpreters spawned by email/web content, or unknown binaries — are strong indicators of post-exploitation persistence being established after initial compromise.
// Hunt: schtasks.exe invoked by unusual parent processes (post-exploitation pattern)
DeviceProcessEvents
| where Timestamp > ago(7d)
| where FileName =~ "schtasks.exe"
| where ProcessCommandLine has_any ("/create", "/change")
| where InitiatingProcessFileName !in~ (
"msiexec.exe", "setup.exe", "install.exe", "ccmexec.exe",
"sccmexec.exe", "powershell.exe", "pwsh.exe", "cmd.exe",
"explorer.exe", "services.exe", "svchost.exe", "taskhost.exe",
"taskhostw.exe", "wusa.exe", "WindowsUpdate.exe"
)
| summarize
Count = count(),
Devices = dcount(DeviceName),
Commands = make_set(ProcessCommandLine, 10),
FirstSeen = min(Timestamp),
LastSeen = max(Timestamp)
by InitiatingProcessFileName, AccountName
| sort by Count desc index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=1
Image="*\\schtasks.exe" (CommandLine="*/create*" OR CommandLine="*/change*")
NOT (
ParentImage="*\\msiexec.exe" OR ParentImage="*\\setup.exe" OR
ParentImage="*\\ccmexec.exe" OR ParentImage="*\\powershell.exe" OR
ParentImage="*\\cmd.exe" OR ParentImage="*\\explorer.exe" OR
ParentImage="*\\services.exe" OR ParentImage="*\\svchost.exe" OR
ParentImage="*\\wusa.exe"
)
| stats
count as Count,
dc(host) as Devices,
values(CommandLine) as Commands,
earliest(_time) as FirstSeen,
latest(_time) as LastSeen
by ParentImage, User
| sort - Count Hunt for scheduled tasks whose action commands point to user-writable or temporary directories. Production software and legitimate administrative tasks store their binaries in signed, version-controlled locations (Program Files, Windows\System32). Tasks pointing to AppData, Temp, Public, or ProgramData with non-vendor-attributed paths are high-confidence malicious persistence or staging artifacts commonly used by ransomware, RATs, and cryptominers.
// Hunt: Scheduled tasks whose actions point to writable or temporary directories
SecurityEvent
| where TimeGenerated > ago(7d)
| where EventID == 4698
| extend TaskName = extract(@"<TaskName>(.*?)</TaskName>", 1, EventData)
| extend TaskCommand = extract(@"<Command>(.*?)</Command>", 1, EventData)
| extend TaskArgs = extract(@"<Arguments>(.*?)</Arguments>", 1, EventData)
| extend FullAction = strcat(TaskCommand, " ", TaskArgs)
| where FullAction has_any (
"\\AppData\\", "\\Temp\\", "\\tmp\\",
"C:\\Users\\Public\\", "C:\\ProgramData\\",
"C:\\Windows\\Temp\\", "%TEMP%", "%APPDATA%"
)
| where FullAction !has_any ("Google", "Microsoft", "Adobe", "Mozilla", "Oracle", "Dropbox", "Citrix")
| project TimeGenerated, Computer, Account, TaskName, TaskCommand, TaskArgs, FullAction
| sort by TimeGenerated desc index=wineventlog sourcetype="WinEventLog:Security" EventCode=4698
| rex field=Message "Task Name:\s+(?<TaskName>[^\r\n]+)"
| rex field=Message "<Command>(?<TaskCommand>[^<]+)</Command>"
| rex field=Message "<Arguments>(?<TaskArgs>[^<]+)</Arguments>"
| eval FullAction=lower(coalesce(TaskCommand,"") . " " . coalesce(TaskArgs,""))
| where match(FullAction, "(appdata|\\\\temp\\\\|\\\\tmp\\\\|\\\\public\\\\|c:\\\\programdata|%temp%|%appdata%)")
| where NOT match(FullAction, "(google|microsoft|adobe|mozilla|oracle|dropbox|citrix)")
| table _time, host, user, TaskName, TaskCommand, TaskArgs
| sort - _time Hunt for scheduled tasks launching scripting engines at anomalously high frequency across multiple hours — a pattern consistent with C2 beaconing, watchdog re-execution loops, or cryptominer heartbeats. Legitimate scheduled tasks run at predictable fixed intervals (e.g., once daily, once weekly). More than 8 executions of a scripting engine as a task action across 3+ active hours warrants immediate investigation as a potential live implant.
// Hunt: High-frequency task execution from scripting engines (beaconing / watchdog pattern)
DeviceProcessEvents
| where Timestamp > ago(7d)
| where InitiatingProcessFileName in~ ("taskeng.exe", "svchost.exe")
| where FileName in~ (
"powershell.exe", "pwsh.exe", "cmd.exe",
"wscript.exe", "cscript.exe", "mshta.exe",
"regsvr32.exe", "rundll32.exe"
)
| summarize
ExecutionCount = count(),
UniqueHours = dcount(bin(Timestamp, 1h)),
Commands = make_set(ProcessCommandLine, 5),
FirstSeen = min(Timestamp),
LastSeen = max(Timestamp)
by DeviceName, AccountName, FileName, InitiatingProcessFileName
| where ExecutionCount > 8 and UniqueHours > 2
| sort by ExecutionCount desc index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-TaskScheduler/Operational" EventCode=200
| rex field=Message "Task Name:\s+(?<TaskName>[^\r\n]+)"
| rex field=Message "Action Name:\s+(?<ActionName>[^\r\n]+)"
| where match(lower(ActionName), "(powershell|cmd\.exe|wscript|cscript|mshta|regsvr32|rundll32)")
| timechart span=1h count by TaskName
| stats
sum(*) as TotalExec,
count as ActiveHours
by TaskName
| where TotalExec > 8 AND ActiveHours > 2
| sort - TotalExec Atomic Red Team Tests
Creates a scheduled task configured to run a benign command (whoami /priv) as SYSTEM at system startup. This simulates the most common adversary pattern for privileged persistence: using /sc onstart and /ru SYSTEM to ensure malicious code executes before user logon with the highest available privileges. The /f flag suppresses the confirmation prompt, matching observed malware behavior (e.g., Lokibot, TrickBot persistence mechanisms).
Command
schtasks /create /tn "\Microsoft\Windows\df00tech-test" /tr "cmd.exe /c whoami /priv > C:\Windows\Temp\df00tech-task-output.txt" /sc onstart /ru SYSTEM /f Cleanup
schtasks /delete /tn "\Microsoft\Windows\df00tech-test" /f
del C:\Windows\Temp\df00tech-task-output.txt 2>nul Expected Telemetry
Sysmon Event ID 1: schtasks.exe with CommandLine containing '/create', '/ru SYSTEM', '/sc onstart', and '/f'. Security Event ID 4698 in Windows Security log with TaskName=\Microsoft\Windows\df00tech-test and TaskPrincipal referencing SYSTEM (S-1-5-18). TaskScheduler Operational Event ID 106 (task registered). Task XML created at C:\Windows\System32\Tasks\Microsoft\Windows\df00tech-test.
Expected Detection
KQL Branch 1 fires: RunAsSystem=true, SuspicionScore >= 1. KQL Branch 2 fires on Security Event 4698 with SYSTEM principal. SPL Branch fires: RunAsSystem=1, SuspicionScore >= 1. Task visible in TaskScheduler Operational log Event 106.
Creates a scheduled task using PowerShell's Register-ScheduledTask cmdlet with a Base64-encoded command as the action argument. This technique is used by threat actors including Cobalt Strike operators and ransomware families (REvil, LockBit) to obscure the task payload from simple command-line inspection. Creating the task via PowerShell COM interface rather than schtasks.exe also bypasses some schtasks-specific process creation monitoring.
Command
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NonInteractive -WindowStyle Hidden -EncodedCommand dwBoAG8AYQBtAGkA'
$trigger = New-ScheduledTaskTrigger -AtLogOn
$settings = New-ScheduledTaskSettingsSet -Hidden -ExecutionTimeLimit 0
Register-ScheduledTask -TaskName 'df00tech-encoded-test' -Action $action -Trigger $trigger -Settings $settings -Force Cleanup
Unregister-ScheduledTask -TaskName 'df00tech-encoded-test' -Confirm:$false Expected Telemetry
Sysmon Event ID 1: powershell.exe executing Register-ScheduledTask via ScheduledTasks module. Security Event ID 4698 with TaskName=df00tech-encoded-test and Action Command=powershell.exe with '-EncodedCommand' in Arguments. TaskScheduler Operational Event ID 106. Task XML in C:\Windows\System32\Tasks\df00tech-encoded-test with Hidden=true and encoded argument visible in task XML.
Expected Detection
KQL Branch 2 fires on Security Event 4698 with task arguments containing 'EncodedCommand' and 'Hidden'. SPL fires with ScriptExecution=1 and EncodedPayload=1, SuspicionScore >= 2. Hunting query for tasks with scripting engines in action also triggers. Combined with T1059.001 detection pattern for the PowerShell process.
Attempts to create a scheduled task on a remote system using the /s flag with the current user context. This simulates lateral movement via scheduled tasks, a technique used extensively by APT groups (APT41, HAFNIUM, FIN7) to propagate through environments using stolen credentials. The target is localhost (127.0.0.1) to keep this test safe while still triggering the /s flag telemetry that detections look for.
Command
schtasks /create /tn "df00tech-remote-test" /tr "cmd.exe /c hostname" /sc once /st 23:59 /s 127.0.0.1 /f Cleanup
schtasks /delete /tn "df00tech-remote-test" /s 127.0.0.1 /f Expected Telemetry
Sysmon Event ID 1: schtasks.exe with CommandLine containing '/s 127.0.0.1' and '/create'. Sysmon Event ID 3: outbound network connection to 127.0.0.1 on port 445 (SMB) or 135 (RPC/DCOM) for remote task registration. Security Event ID 4648 (logon with explicit credentials) if /u and /p are provided. Security Event ID 4698 on the target for the new task.
Expected Detection
KQL Branch 1 fires: RemoteTask=true (/s flag detected), SuspicionScore >= 1. SPL fires: RemoteTask=1, SuspicionScore >= 1. Hunting query for unusual parent processes also triggers. Cross-correlation with Sysmon network events to 127.0.0.1 SMB port confirms remote task creation behavior.
Adds a crontab entry that simulates the download-and-execute pattern used by cryptominers (TeamTNT, LemonDuck), botnets (Mirai variants), and Linux RATs. The test uses a benign command (id) rather than a real download to avoid impact, but the crontab structure with bash -c and command substitution matches real-world malicious crontab entries observed in the wild.
Command
(crontab -l 2>/dev/null; echo '*/5 * * * * /bin/bash -c "id > /tmp/df00tech-cron-out.txt"') | crontab -
crontab -l Cleanup
crontab -l | grep -v 'df00tech' | crontab -
rm -f /tmp/df00tech-cron-out.txt Expected Telemetry
Auditd: openat/write syscall to /var/spool/cron/crontabs/<username> or /tmp/crontab.XXXXXX (temp file used by crontab command). Process creation for 'crontab' binary with '-' as argument (reading from stdin). After 5 minutes: crond/cron spawns /bin/bash with the -c argument, creating /tmp/df00tech-cron-out.txt. Syslog shows cron job execution: 'CRON[PID]: (user) CMD (/bin/bash -c ...'.
Expected Detection
Linux auditd rules watching /var/spool/cron/ for write access trigger. Syslog/auditd detection rules for crontab modification by non-root users. SIEM rules monitoring cron daemon process creation events (Syslog table in Sentinel, index=linux_secure or index=syslog in Splunk) for bash -c execution patterns.
Creates a scheduled task by importing a crafted XML file and placing it under a Microsoft Windows task path to blend into the legitimate task tree. XML import via /xml bypasses some command-line parameter monitoring that looks for /tr (task run) flags, and the masqueraded task name reduces visibility in casual Task Scheduler UI reviews. This technique is used by BRONZE BUTLER (Daserf), APT10, and multiple ransomware families for durable persistence.
Command
$xmlContent = @'
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<Principals><Principal id="Author"><LogonType>InteractiveToken</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals>
<Triggers><TimeTrigger><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled><Repetition><Interval>PT5M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition></TimeTrigger></Triggers>
<Actions Context="Author"><Exec><Command>cmd.exe</Command><Arguments>/c whoami /all > C:\Windows\Temp\df00tech-xml-out.txt</Arguments></Exec></Actions>
<Settings><Enabled>true</Enabled><Hidden>true</Hidden><ExecutionTimeLimit>PT1M</ExecutionTimeLimit></Settings>
</Task>
'@
$xmlContent | Out-File -FilePath "$env:TEMP\df00tech-task.xml" -Encoding Unicode
schtasks /create /tn "\Microsoft\Windows\WindowsDefender\df00tech-DefenderUpdate" /xml "$env:TEMP\df00tech-task.xml" /f Cleanup
schtasks /delete /tn "\Microsoft\Windows\WindowsDefender\df00tech-DefenderUpdate" /f
del "$env:TEMP\df00tech-task.xml" 2>nul
del C:\Windows\Temp\df00tech-xml-out.txt 2>nul Expected Telemetry
Sysmon Event ID 1: schtasks.exe with CommandLine containing '/xml' and task name under \Microsoft\Windows\WindowsDefender\. Sysmon Event ID 11: XML file creation in %TEMP%. Security Event ID 4698 with full task XML in EventData — shows Hidden=true, 5-minute repeating trigger, and cmd.exe action. TaskScheduler Operational Event 106. Task XML persisted at C:\Windows\System32\Tasks\Microsoft\Windows\WindowsDefender\df00tech-DefenderUpdate.
Expected Detection
KQL Branch 2 fires on Security Event 4698 with task action containing 'cmd.exe' and arguments containing 'Temp'. SPL Branch 2 fires with SuspiciousAction=1. Hunting query for tasks in writable paths fires. The Hidden=true XML flag combined with a repeating trigger and cmd.exe action constitutes a high-suspicion pattern. Analyst should verify the task against the known-good Windows Defender task list.