threat hunting

Hunting for Suspicious Scheduled Tasks

Hunt for adversary persistence and execution via Windows scheduled tasks by analyzing task creation events, suspicious task properties, and unusual execution patterns that indicate T1053.005 abuse.

endpoint-detectionmitre-t1053-005persistencescheduled-tasksthreat-huntingwindows
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • When proactively hunting for persistence mechanisms in Windows environments
  • After detecting schtasks.exe or at.exe usage in process creation logs
  • When investigating malware that survives reboots and user logoffs
  • During incident response to enumerate all persistence on compromised systems
  • When Windows Security Event ID 4698 (Scheduled Task Created) fires for unusual tasks

Prerequisites

  • Windows Security Event ID 4698/4699/4702 (Task Created/Deleted/Updated)
  • Sysmon Event ID 1 for schtasks.exe process creation with command lines
  • Windows Task Scheduler operational log (Microsoft-Windows-TaskScheduler/Operational)
  • PowerShell logging for Register-ScheduledTask cmdlet usage
  • Access to Task Scheduler XML definitions on endpoints

Workflow

  1. Enumerate All Scheduled Tasks: Collect complete task inventory from target systems using schtasks /query /fo CSV /v or Get-ScheduledTask PowerShell cmdlet.
  2. Monitor Task Creation Events: Track Event ID 4698 for new task creation, correlating with the creating process and user account context.
  3. Analyze Task Actions: Examine what each task executes. Flag tasks running scripts (PowerShell, cmd, wscript), binaries from user-writable paths (TEMP, AppData, Downloads), or encoded/obfuscated commands.
  4. Check Task Triggers: Review trigger conditions. Tasks triggered by system startup, user logon, or short intervals (1-5 minutes) warrant investigation.
  5. Identify Hidden or Disguised Tasks: Hunt for tasks with names mimicking legitimate Windows tasks, tasks with Security Descriptor modifications hiding them from standard enumeration, or tasks stored in non-standard registry locations.
  6. Correlate with Process Execution: Match scheduled task execution events with process creation logs to confirm what actually runs.
  7. Baseline and Diff: Compare current task inventory against known-good baselines to identify new, modified, or unexpected tasks.

Detection Queries

Splunk -- Scheduled Task Creation

index=wineventlog EventCode=4698
| spath output=TaskName path=EventData.TaskName
| spath output=TaskContent path=EventData.TaskContent
| where NOT match(TaskName, "(?i)(\\\\Microsoft\\\\|\\\\Windows\\\\)")
| table _time Computer SubjectUserName TaskName TaskContent

Splunk -- Schtasks.exe Suspicious Usage

index=sysmon EventCode=1 Image="*\\schtasks.exe"
| where match(CommandLine, "(?i)/create")
| where match(CommandLine, "(?i)(powershell|cmd|wscript|cscript|mshta|rundll32|regsvr32|http|https|\\\\temp\\\\|\\\\appdata\\\\)")
| table _time Computer User CommandLine ParentImage

KQL -- Microsoft Sentinel

SecurityEvent
| where EventID == 4698
| extend TaskName = tostring(EventData.TaskName)
| extend TaskContent = tostring(EventData.TaskContent)
| where TaskContent has_any ("powershell", "cmd.exe", "wscript", "http://", "https://", "\\Temp\\", "\\AppData\\")
| project TimeGenerated, Computer, Account, TaskName, TaskContent

Common Scenarios

  1. Cobalt Strike Persistence: Creates scheduled tasks via schtasks.exe to execute PowerShell download cradles at user logon intervals.
  2. Ransomware Staging: Task created to run encryption payload at a future time, often during off-hours for maximum impact.
  3. Hidden Task via SD Modification: Attacker modifies Security Descriptor of scheduled task to hide it from normal enumeration while maintaining execution.
  4. COM Handler Abuse: Task uses COM handler rather than direct executable path, making action inspection more complex.
  5. Lateral Movement via Tasks: Remote scheduled task creation using schtasks /create /s REMOTE_HOST for execution on other systems.

Output Format

Hunt ID: TH-SCHTASK-[DATE]-[SEQ]
Host: [Hostname]
Task Name: [Full task path]
Action: [Command/Script executed]
Trigger: [Startup/Logon/Timer/Event]
Created By: [User account]
Created From: [Local/Remote]
Creation Time: [Timestamp]
Run As: [Execution account]
Risk Level: [Critical/High/Medium/Low]
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.9 KB

API Reference: Hunting for Suspicious Scheduled Tasks

Windows Event IDs

Event ID Source Description
4698 Security Scheduled task created
4699 Security Scheduled task deleted
4702 Security Scheduled task updated
106 TaskScheduler Task registered
200/201 TaskScheduler Task executed / completed

python-evtx

import Evtx.Evtx as evtx
import xml.etree.ElementTree as ET
 
with evtx.Evtx("Security.evtx") as log:
    for record in log.records():
        root = ET.fromstring(record.xml())
        ns = {"ns": "http://schemas.microsoft.com/win/2004/08/events/event"}
        eid = root.find(".//ns:EventID", ns).text
        if eid == "4698":
            data = {d.get("Name"): d.text
                    for d in root.findall(".//ns:Data", ns)}

Splunk SPL

index=wineventlog EventCode=4698
| spath output=TaskName path=EventData.TaskName
| spath output=TaskContent path=EventData.TaskContent
| where NOT match(TaskName, "\\\\Microsoft\\\\Windows\\\\")
| where match(TaskContent, "(?i)(powershell|cmd|wscript|http)")
| table _time Computer SubjectUserName TaskName TaskContent

KQL (Microsoft Sentinel)

SecurityEvent
| where EventID == 4698
| extend TaskContent = tostring(EventData.TaskContent)
| where TaskContent has_any ("powershell", "cmd.exe", "Temp", "AppData")
| project TimeGenerated, Computer, Account, TaskContent

PowerShell Enumeration

Get-ScheduledTask | Where-Object {
    $_.Actions.Execute -match 'powershell|cmd|wscript' -or
    $_.Actions.Execute -match '\\Temp\\|\\AppData\\'
} | Select-Object TaskName, TaskPath, @{N='Action';E={$_.Actions.Execute}}

References

standards.md1.4 KB

Standards and References - Suspicious Scheduled Tasks

MITRE ATT&CK References

Technique Name Usage
T1053.005 Scheduled Task Primary persistence/execution technique
T1053.003 Cron (Linux) Scheduled execution on Linux
T1078 Valid Accounts Tasks running under legitimate accounts

Windows Event IDs

Event ID Source Description
4698 Security Scheduled task created
4699 Security Scheduled task deleted
4700 Security Scheduled task enabled
4701 Security Scheduled task disabled
4702 Security Scheduled task updated
106 TaskScheduler/Operational Task registered
200 TaskScheduler/Operational Action started
201 TaskScheduler/Operational Action completed

Suspicious Task Indicators

Indicator Description
User-writable paths Actions executing from TEMP, AppData, Downloads
Encoded commands Base64 or -EncodedCommand in arguments
Script interpreters PowerShell, cmd, wscript, cscript as actions
Short intervals Trigger repeating every 1-5 minutes
System startup trigger Task runs at boot for persistence
Remote creation Task created from remote system
Name mimicry Task name similar to legitimate Windows tasks
Hidden SD Security Descriptor modified to hide task
workflows.md1.2 KB

Detailed Hunting Workflow - Suspicious Scheduled Tasks

Phase 1: Task Enumeration

# Full task export with details
Get-ScheduledTask | Where-Object { $_.TaskPath -notmatch "\\Microsoft\\" } |
    ForEach-Object { $_ | Get-ScheduledTaskInfo; $_.Actions | Select-Object Execute, Arguments }
 
# Check for hidden tasks in registry
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree" -Recurse

Phase 2: SIEM Analysis

index=wineventlog EventCode=4698
| spath output=TaskName path=EventData.TaskName
| spath output=TaskContent path=EventData.TaskContent
| rex field=TaskContent "<Command>(?<cmd>[^<]+)</Command>"
| rex field=TaskContent "<Arguments>(?<args>[^<]+)</Arguments>"
| table _time Computer SubjectUserName TaskName cmd args

Phase 3: Remote Task Creation Detection

index=sysmon EventCode=1 Image="*\\schtasks.exe"
| where match(CommandLine, "(?i)/create.*/s\s+")
| rex field=CommandLine "/s\s+(?<remote_host>\S+)"
| table _time Computer User remote_host CommandLine

Phase 4: Response

  1. Remove malicious scheduled tasks
  2. Check task XML definitions for hidden parameters
  3. Audit all non-Microsoft scheduled tasks across fleet
  4. Deploy detection rules for suspicious task creation

Scripts 2

agent.py6.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for hunting suspicious scheduled tasks on Windows endpoints."""

import json
import argparse
import re
import xml.etree.ElementTree as ET
from datetime import datetime

try:
    import Evtx.Evtx as evtx
except ImportError:
    evtx = None


SUSPICIOUS_ACTIONS = [
    r"powershell", r"pwsh", r"cmd\.exe.*/c", r"wscript", r"cscript",
    r"mshta", r"rundll32", r"regsvr32", r"certutil",
    r"bitsadmin", r"msiexec.*http",
]

SUSPICIOUS_PATHS = [
    r"\\temp\\", r"\\tmp\\", r"\\appdata\\", r"\\downloads\\",
    r"\\public\\", r"\\programdata\\", r"\\users\\.*\\desktop\\",
    r"c:\\windows\\temp",
]

LEGITIMATE_TASK_PREFIXES = [
    "\\Microsoft\\Windows\\", "\\Microsoft\\Office\\",
    "\\Microsoft\\EdgeUpdate\\",
]


def parse_schtasks_csv(csv_path):
    """Parse output of schtasks /query /fo CSV /v."""
    import csv
    tasks = []
    with open(csv_path, newline="", encoding="utf-8-sig") as f:
        reader = csv.DictReader(f)
        for row in reader:
            tasks.append({
                "hostname": row.get("HostName", ""),
                "task_name": row.get("TaskName", ""),
                "status": row.get("Status", ""),
                "task_to_run": row.get("Task To Run", ""),
                "run_as_user": row.get("Run As User", ""),
                "schedule_type": row.get("Schedule Type", ""),
                "author": row.get("Author", ""),
            })
    return tasks


def analyze_tasks(tasks):
    """Analyze scheduled tasks for suspicious properties."""
    findings = []
    for task in tasks:
        name = task.get("task_name", "")
        action = task.get("task_to_run", "")
        run_as = task.get("run_as_user", "")
        is_legit_prefix = any(name.startswith(p) for p in LEGITIMATE_TASK_PREFIXES)
        risk_score = 0
        reasons = []
        for pattern in SUSPICIOUS_ACTIONS:
            if re.search(pattern, action, re.IGNORECASE):
                risk_score += 30
                reasons.append(f"suspicious_action:{pattern}")
        for pattern in SUSPICIOUS_PATHS:
            if re.search(pattern, action, re.IGNORECASE):
                risk_score += 25
                reasons.append(f"suspicious_path:{pattern}")
        if run_as and "SYSTEM" in run_as.upper():
            risk_score += 15
            reasons.append("runs_as_system")
        if not is_legit_prefix and name.count("\\") <= 1:
            risk_score += 10
            reasons.append("non_standard_location")
        if re.search(r"(http|https|ftp)://", action, re.IGNORECASE):
            risk_score += 40
            reasons.append("network_url_in_action")
        if re.search(r"-enc\s|encodedcommand", action, re.IGNORECASE):
            risk_score += 35
            reasons.append("encoded_command")
        if risk_score > 0:
            severity = "CRITICAL" if risk_score >= 60 else "HIGH" if risk_score >= 30 else "MEDIUM"
            findings.append({
                "task_name": name,
                "action": action[:500],
                "run_as_user": run_as,
                "risk_score": risk_score,
                "severity": severity,
                "reasons": reasons,
                "hostname": task.get("hostname", ""),
            })
    return sorted(findings, key=lambda x: x["risk_score"], reverse=True)


def hunt_evtx_4698(evtx_path):
    """Hunt Event ID 4698 (scheduled task creation) in EVTX."""
    if evtx is None:
        return []
    findings = []
    with evtx.Evtx(evtx_path) as log:
        for record in log.records():
            xml_str = record.xml()
            try:
                root = ET.fromstring(xml_str)
                ns = {"ns": "http://schemas.microsoft.com/win/2004/08/events/event"}
                eid_el = root.find(".//ns:EventID", ns)
                if eid_el is None or eid_el.text != "4698":
                    continue
                data = {}
                for d in root.findall(".//ns:Data", ns):
                    data[d.get("Name", "")] = d.text or ""
                task_name = data.get("TaskName", "")
                task_content = data.get("TaskContent", "")
                is_suspicious = any(
                    re.search(p, task_content, re.IGNORECASE) for p in SUSPICIOUS_ACTIONS)
                if is_suspicious:
                    findings.append({
                        "timestamp": record.timestamp().isoformat(),
                        "task_name": task_name,
                        "user": data.get("SubjectUserName", ""),
                        "task_content_preview": task_content[:500],
                        "severity": "HIGH",
                    })
            except ET.ParseError:
                continue
    return findings


def generate_sigma_rule():
    """Generate Sigma rule for suspicious scheduled task creation."""
    return {
        "title": "Suspicious Scheduled Task Created",
        "id": "e4db2c6a-3f1b-4c8d-9e2a-7b5c4d6e8f0a",
        "status": "production",
        "level": "high",
        "logsource": {"product": "windows", "service": "security"},
        "detection": {
            "selection": {"EventID": 4698},
            "filter_legit": {"TaskName|startswith": ["\\Microsoft\\Windows\\", "\\Microsoft\\Office\\"]},
            "suspicious_content": {
                "TaskContent|contains": ["powershell", "cmd /c", "wscript", "mshta",
                                          "\\Temp\\", "\\AppData\\", "http://", "https://"],
            },
            "condition": "selection and not filter_legit and suspicious_content",
        },
        "tags": ["attack.persistence", "attack.execution", "attack.t1053.005"],
    }


def main():
    parser = argparse.ArgumentParser(description="Suspicious Scheduled Tasks Hunter")
    parser.add_argument("--csv", help="schtasks CSV export")
    parser.add_argument("--evtx", help="Security EVTX log file")
    parser.add_argument("--output", default="schtask_hunt_report.json")
    parser.add_argument("--action", choices=["analyze", "hunt_evtx", "sigma", "full"],
                        default="full")
    args = parser.parse_args()

    report = {"generated_at": datetime.utcnow().isoformat(), "findings": {}}

    if args.action in ("analyze", "full") and args.csv:
        tasks = parse_schtasks_csv(args.csv)
        findings = analyze_tasks(tasks)
        report["findings"]["task_analysis"] = findings
        print(f"[+] Suspicious tasks: {len(findings)} / {len(tasks)} total")

    if args.action in ("hunt_evtx", "full") and args.evtx:
        findings = hunt_evtx_4698(args.evtx)
        report["findings"]["evtx_4698"] = findings
        print(f"[+] EVTX 4698 suspicious: {len(findings)}")

    if args.action in ("sigma", "full"):
        report["findings"]["sigma_rule"] = generate_sigma_rule()
        print("[+] Sigma rule generated")

    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    print(f"[+] Report saved to {args.output}")


if __name__ == "__main__":
    main()
process.py4.7 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Suspicious Scheduled Task Detection Script
Analyzes Windows event logs for malicious scheduled task creation,
modification, and execution patterns.
"""

import json
import csv
import argparse
import datetime
import re
from pathlib import Path

SUSPICIOUS_ACTION_PATTERNS = [
    (r"(?i)powershell", "powershell_execution", "HIGH"),
    (r"(?i)(cmd\.exe|cmd\s/c)", "command_shell", "HIGH"),
    (r"(?i)(wscript|cscript)", "script_execution", "HIGH"),
    (r"(?i)(mshta|rundll32|regsvr32)", "lolbin_execution", "CRITICAL"),
    (r"(?i)(http|https)://", "network_download", "CRITICAL"),
    (r"(?i)(\\temp\\|\\appdata\\|\\downloads\\)", "user_writable_path", "HIGH"),
    (r"(?i)(-enc\s|-encodedcommand)", "encoded_command", "CRITICAL"),
    (r"(?i)(base64|frombase64)", "base64_content", "HIGH"),
]

LEGITIMATE_TASK_PATHS = [
    r"(?i)\\Microsoft\\",
    r"(?i)\\Windows\\",
    r"(?i)\\Adobe\\",
    r"(?i)\\Google\\",
]


def parse_events(input_path: str) -> list[dict]:
    path = Path(input_path)
    events = []
    if path.suffix == ".json":
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
            events = data if isinstance(data, list) else data.get("events", [])
    elif path.suffix == ".csv":
        with open(path, "r", encoding="utf-8-sig") as f:
            events = [dict(row) for row in csv.DictReader(f)]
    return events


def detect_suspicious_tasks(events: list[dict]) -> list[dict]:
    findings = []
    for event in events:
        event_code = str(event.get("EventCode", event.get("EventID", "")))
        computer = event.get("Computer", event.get("host", ""))
        timestamp = event.get("TimeCreated", event.get("_time", ""))
        user = event.get("SubjectUserName", event.get("user", ""))

        if event_code == "4698":
            task_name = event.get("TaskName", "")
            task_content = event.get("TaskContent", "")
            if any(re.search(p, task_name) for p in LEGITIMATE_TASK_PATHS):
                continue

            cmd_match = re.search(r"<Command>([^<]+)</Command>", task_content)
            args_match = re.search(r"<Arguments>([^<]+)</Arguments>", task_content)
            command = cmd_match.group(1) if cmd_match else ""
            arguments = args_match.group(1) if args_match else ""
            full_action = f"{command} {arguments}"

            for pattern, category, severity in SUSPICIOUS_ACTION_PATTERNS:
                if re.search(pattern, full_action):
                    findings.append({
                        "timestamp": timestamp, "computer": computer, "user": user,
                        "task_name": task_name, "command": command,
                        "arguments": arguments, "category": category,
                        "severity": severity, "technique": "T1053.005",
                    })
                    break

        elif event_code == "1":
            image = event.get("Image", "")
            cmdline = event.get("CommandLine", "")
            if "schtasks.exe" in image.lower() and "/create" in cmdline.lower():
                for pattern, category, severity in SUSPICIOUS_ACTION_PATTERNS:
                    if re.search(pattern, cmdline):
                        findings.append({
                            "timestamp": timestamp, "computer": computer, "user": user,
                            "task_name": "via_schtasks",
                            "command": image, "arguments": cmdline,
                            "category": f"schtasks_{category}",
                            "severity": severity, "technique": "T1053.005",
                        })
                        break

    return sorted(findings, key=lambda x: {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2}.get(x["severity"], 3))


def run_hunt(input_path: str, output_dir: str) -> None:
    print(f"[*] Scheduled Task Hunt - {datetime.datetime.now().isoformat()}")
    events = parse_events(input_path)
    findings = detect_suspicious_tasks(events)
    print(f"[!] Suspicious task detections: {len(findings)}")

    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)
    with open(output_path / "schtask_findings.json", "w", encoding="utf-8") as f:
        json.dump({"hunt_id": f"TH-SCHTASK-{datetime.date.today().isoformat()}",
                    "findings": findings}, f, indent=2)
    print(f"[+] Results written to {output_dir}")


def main():
    parser = argparse.ArgumentParser(description="Suspicious Scheduled Task Detection")
    parser.add_argument("--input", "-i", required=True)
    parser.add_argument("--output", "-o", default="./schtask_hunt_output")
    args = parser.parse_args()
    run_hunt(args.input, args.output)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 0.8 KB
Keep exploring