Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

23.2 KB
Raw Blame
"""
Windows Scheduled Tasks Enumeration - Privilege Escalation Path Analysis
MITRE: T1053.005 (Scheduled Task/Job), T1574.001 (DLL Search Order Hijacking)

Enumerates scheduled tasks on the target via impacket TSCH RPC and identifies:
  1. Tasks running as SYSTEM, high-privilege domain accounts, or Administrators
  2. Tasks whose binary or script path is writable by non-admin users
     (if the path is writable, the task binary can be replaced for privesc)
  3. Tasks running from user-writable directories (%TEMP%, %APPDATA%, etc.)
  4. Misconfigured task permissions (task itself writable by low-priv users)
  5. Tasks that run at logon or on a schedule that could be abused for persistence

This module is ENUMERATION ONLY - it reads task XML and checks paths.
No tasks are created, modified, or triggered.

OPSEC: LOW-MEDIUM - connects via SMB + TSCH RPC (\\pipe\\atsvc).
Generates: SMB connection events. No process execution on target.
"""
from __future__ import annotations

import asyncio
import re
from typing import Any

try:
    import defusedxml.ElementTree as ET
    from defusedxml.ElementTree import fromstring as _xml_fromstring
except ImportError:
    import xml.etree.ElementTree as ET  # nosec B405
    from xml.etree.ElementTree import fromstring as _xml_fromstring  # nosec B405, B314

from ares.core.campaign import Finding, Severity
from ares.core.logger import audit, get_logger
from ares.core.security import sanitize_hostname
from ares.core.tracing import trace_module
from ares.modules.base import BaseModule, OpsecLevel
from ares.modules.params import ScheduledTasksEnumParams
from ares.sdk import (
    EvidenceRecord,
    LockoutCircuitBreaker,
    ModuleResult,
    NetworkPermission,
    ProcessPermission,
    module_contract,
)

logger = get_logger("ares.modules.windows.scheduled_tasks_enum")


# ── High-privilege user indicators ────────────────────────────────────────────
_HIGH_PRIV_PATTERNS: list[str] = [
    "system",
    "nt authority\\system",
    "nt authority\\local service",
    "nt authority\\network service",
    "builtin\\administrators",
    "domain admins",
    "enterprise admins",
    "schema admins",
]

# ── Writable path indicators (user-controlled locations) ──────────────────────
_USER_WRITABLE_INDICATORS: list[str] = [
    "%temp%",
    "%tmp%",
    "%appdata%",
    "%localappdata%",
    "\\users\\",
    "\\temp\\",
    "\\tmp\\",
    "c:\\programdata",
]

# ── Interesting task folders to enumerate ─────────────────────────────────────
_TASK_FOLDERS: list[str] = [
    "\\",
    "\\Microsoft\\Windows\\",
    "\\Microsoft\\Windows\\WindowsUpdate\\",
]


def _parse_task_xml(xml_str: str) -> dict[str, Any]:
    """
    Parse task XML to extract:
      - Run as user (Principal UserId or GroupId)
      - Run level (HighestAvailable, LimitedAccess)
      - Actions (Exec command + arguments, ComHandler)
      - Triggers (type, start boundary)
    """
    info: dict[str, Any] = {
        "run_as":      "",
        "run_level":   "",
        "actions":     [],
        "triggers":    [],
        "parse_error": "",
    }
    if not xml_str:
        return info
    try:
        # Strip namespace for simpler parsing
        xml_clean = re.sub(r'\s+xmlns(?::\w+)?="[^"]+"', "", xml_str)
        root = _xml_fromstring(xml_clean)  # nosec: B314

        # Principal
        for p in root.iter("Principal"):
            uid = p.find("UserId")
            gid = p.find("GroupId")
            rl  = p.find("RunLevel")
            if uid is not None and uid.text:
                info["run_as"]    = uid.text.strip()
            elif gid is not None and gid.text:
                info["run_as"]    = gid.text.strip()
            if rl is not None and rl.text:
                info["run_level"] = rl.text.strip()

        # Actions
        for action in root.iter("Actions"):
            for exec_el in action.iter("Exec"):
                cmd  = exec_el.find("Command")
                args = exec_el.find("Arguments")
                info["actions"].append({
                    "type":    "Exec",
                    "command": cmd.text.strip()  if (cmd  and cmd.text)  else "",
                    "args":    args.text.strip() if (args and args.text) else "",
                })
            for com_el in action.iter("ComHandler"):
                clsid = com_el.find("ClassId")
                info["actions"].append({
                    "type":   "ComHandler",
                    "classid": clsid.text.strip() if (clsid and clsid.text) else "",
                })

        # Triggers (first 3)
        for trigger in list(root.iter("Triggers"))[0:1]:
            for child in list(trigger)[:3]:
                tag = child.tag.split("}")[-1]
                sb  = child.find("StartBoundary")
                info["triggers"].append({
                    "type":  tag,
                    "start": sb.text.strip() if (sb and sb.text) else "",
                })

    except ET.ParseError as e:
        info["parse_error"] = str(e)[:100]
    return info


@module_contract(
    permissions=[
        NetworkPermission(ports=[139, 445], protocols=["tcp"]),
        ProcessPermission(allow_subprocesses=False),
    ],
    circuit_breaker=LockoutCircuitBreaker(),
    params_model=ScheduledTasksEnumParams,
)
class ScheduledTasksEnumModule(BaseModule):
    """
    windows.scheduled_tasks_enum - Enumerate scheduled tasks via TSCH RPC and identify high-privilege tasks with writable binary pa

    OPSEC: LOW
    MITRE: "T1053.005", "T1082"
    REQUIRES: "local_admin_creds"
    OUTPUTS:  "scheduled_tasks", "privesc_vectors"
    """
    MODULE_ID          = "windows.scheduled_tasks_enum"
    MODULE_NAME        = "Scheduled Tasks Enumeration"
    MODULE_CATEGORY    = "windows"
    MODULE_DESCRIPTION = (
        "Enumerate scheduled tasks via TSCH RPC and identify high-privilege tasks "
        "with writable binary paths - privilege escalation path analysis"
    )
    MODULE_AUTHOR      = "ARES Team <[email protected]>"
    OPSEC_LEVEL        = OpsecLevel.LOW
    REQUIRES           = ["local_admin_creds"]
    OUTPUTS            = ["scheduled_tasks", "privesc_vectors"]
    MITRE_TECHNIQUES   = ["T1053.005", "T1082"]
    PARAMS_MODEL       = ScheduledTasksEnumParams

    async def validate(self, ctx: "Any") -> None:
        """Pre-flight param checks before any network call."""
        from ares.core.context import ExecutionContext
        from ares.core.errors import ModuleValidationError
        if not isinstance(ctx, ExecutionContext):
            return
        if isinstance(ctx.params, dict):
            if not ctx.params.get("target") and getattr(ctx, "target", None):
                ctx.params["target"] = ctx.target
            if not ctx.params.get("domain") and getattr(ctx, "domain", None):
                ctx.params["domain"] = ctx.domain
            if not ctx.params.get("username") and hasattr(ctx, "best_credential"):
                cred = ctx.best_credential()
                if cred and cred.username:
                    ctx.params["username"] = cred.username
        target = getattr(ctx, "target", "") or (ctx.params.get("target", "") if isinstance(ctx.params, dict) else getattr(ctx.params, "target", ""))
        if not target:
            raise ModuleValidationError(
                f"{self.MODULE_ID} requires 'target' - IP or hostname.",
                module_id=self.MODULE_ID, field="target",
            )
        username = (
            ctx.params.get("username", "")
            if isinstance(ctx.params, dict)
            else getattr(ctx.params, "username", "")
        )
        if not username and hasattr(ctx, "best_credential"):
            cred = ctx.best_credential()
            if cred and cred.username:
                username = cred.username
                if isinstance(ctx.params, dict):
                    ctx.params["username"] = username
                elif hasattr(ctx.params, "username"):
                    try:
                        ctx.params.username = username
                    except Exception:
                        pass
        if not username:
            raise ModuleValidationError(
                f"{self.MODULE_ID} requires 'username' - credential username for authentication.",
                module_id=self.MODULE_ID, field="username",
            )
        await super().validate(ctx)

    async def execute(self, ctx: "Any") -> "ModuleResult":
        """ExecutionContext-based entry point (v0.9.0+).
        Thin adapter: extract params from ctx → call run() → return ModuleResult.
        """
        from ares.modules.base import ModuleResult
        if getattr(ctx, "dry_run", False):
            return ModuleResult(
                status="dry_run", module_id=self.MODULE_ID,
                raw={"dry_run": True},
            )
        target   = getattr(ctx, "target", "")
        username = ""
        password = ""
        domain   = getattr(ctx, "domain", "")

        params = getattr(ctx, "params", {})
        if isinstance(params, ScheduledTasksEnumParams):
            target = params.target or target
            username = params.username or ""
            password = params.password.get_secret_value() if hasattr(params.password, "get_secret_value") else (params.password or "")
            domain = params.domain or domain
        elif isinstance(params, dict):
            target = params.get("target") or target
            username = params.get("username", "")
            raw_pass = params.get("password") or params.get("secret", "")
            password = raw_pass.get_secret_value() if hasattr(raw_pass, "get_secret_value") else (raw_pass or "")
            domain = params.get("domain") or domain

        findings, raw = await self.run(
            target=target, username=username, password=password, domain=domain,
        )

        # Cryptographic Evidence Records with SHA-256 Merkle Provenance
        evidence_chain: list[EvidenceRecord] = []
        for finding in findings:
            ev = EvidenceRecord(
                artifact_id=f"windows-tasks-{target.replace('.', '-')}",
                source_target=target,
                collected_by=self.MODULE_ID,
                data={
                    "target": target,
                    "title": finding.title,
                    "severity": str(finding.severity),
                },
                tags=["windows", "scheduled_tasks_enum"],
            )
            evidence_chain.append(ev)

        raw["evidence_chain"] = [e.data for e in evidence_chain]
        raw["evidence_integrity"] = [e.record_hash for e in evidence_chain]

        # Closed-loop Purple Telemetry Synthesis (Sentinel KQL + Sigma YAML)
        kql_rule = (
            "// Microsoft Sentinel - Scheduled Task Enumeration and Modification Detection\n"
            "SecurityEvent\n"
            "| where TimeGenerated > ago(2h)\n"
            "| where (EventID in (4698, 4702) and TaskContent has_any (\"powershell\", \"cmd.exe\", \"cscript\", \"wscript\", \"mshta\"))\n"
            "     or (EventID == 4688 and Process has_any (\"schtasks.exe\") and CommandLine has_any (\"/query\", \"/create\", \"/change\"))\n"
            "| project TimeGenerated, Computer, Account, Process, CommandLine, TaskName"
        )
        sigma_rule = (
            "title: Scheduled Task Enumeration or Suspicious Task Registration\n"
            "id: b8c9d0e1-f2a3-44b5-c6d7-e8f9a0b1c2d3\n"
            "status: experimental\n"
            "description: Detects querying or registration of scheduled tasks invoking command interpreters or scripting engines\n"
            "references:\n"
            "    - https://attack.mitre.org/techniques/T1053/005/\n"
            "author: ARES Purple Team Modernization\n"
            "date: 2026-03-30\n"
            "logsource:\n"
            "    category: process_creation\n"
            "    product: windows\n"
            "detection:\n"
            "    selection_schtasks:\n"
            "        Image|endswith: '\\schtasks.exe'\n"
            "        CommandLine|contains:\n"
            "            - '/query'\n"
            "            - '/create'\n"
            "    condition: selection_schtasks\n"
            "level: medium\n"
            "tags:\n"
            "    - attack.persistence\n"
            "    - attack.privilege_escalation\n"
            "    - attack.t1053.005"
        )
        raw.setdefault("loot", {})
        raw["loot"]["detection_kql"] = kql_rule
        raw["loot"]["detection_sigma"] = sigma_rule
        privesc_vecs = raw.get("privesc_vectors", [])
        raw["writable_task_binaries_found"] = any(
            "writable" in str(v).lower() for v in privesc_vecs
        )
        raw["unquoted_task_paths_detected"] = any(
            "unquoted" in str(v).lower() for v in privesc_vecs
        )
        raw["custom_scheduled_tasks_count"] = len(raw.get("scheduled_tasks", []))
        raw["scheduled_tasks_audited"] = True

        return ModuleResult(
            status="success" if findings else "partial",
            findings=findings, raw=raw, module_id=self.MODULE_ID,
            execution_id=getattr(ctx, "execution_id", ""),
        )

    @trace_module("windows.scheduled_tasks_enum")
    async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:
        target   = sanitize_hostname(kwargs.get("target", ""))
        username = kwargs.get("username", "")
        password = kwargs.get("password", "") or kwargs.get("secret", "")
        domain   = kwargs.get("domain", "")
        dry_run  = kwargs.get("dry_run", False)

        if not target or not username:
            logger.warning(
                "scheduled_tasks_enum_missing_params",
                target=target,
                has_username=bool(username),
            )
            return [], {"error": "target and username required"}
        if dry_run:
            return [], {"dry_run": True}

        try:
            from impacket.dcerpc.v5 import transport, tsch
            from impacket.dcerpc.v5.tsch import (
                TASK_ENUM_HIDDEN,
                hSchRpcEnumFolders,
                hSchRpcEnumTasks,
                hSchRpcRetrieveTask,
            )
        except ImportError:
            logger.warning("scheduled_tasks_enum_impacket_missing", target=target)
            return [], {"error": "impacket not installed - pip install ares-redteam[ad]"}

        logger.info("scheduled_tasks_enum_start", target=target, username=username)
        audit("scheduled_tasks_enum", actor=username, source="operator",
              target=target, technique="T1053.005")

        await self.before_request(target, "smb")

        loop = asyncio.get_running_loop()

        def _enum_tasks() -> dict[str, Any]:
            tasks:  list[dict[str, Any]] = []
            errors: list[str] = []

            try:
                string_binding = f"ncacn_np:{target}[\\pipe\\atsvc]"
                rpc_transport  = transport.DCERPCTransportFactory(string_binding)
                rpc_transport.set_credentials(
                    username, password, domain, "", ""
                )
                dce = rpc_transport.get_dce_rpc()
                dce.connect()
                dce.bind(tsch.MSRPC_UUID_TSCHS)

                def _enum_folder(folder: str) -> None:
                    # Enumerate tasks in this folder
                    try:
                        resp = hSchRpcEnumTasks(dce, folder, flags=TASK_ENUM_HIDDEN,
                                               startIndex=0, cRequested=100)
                        task_names = resp["pNames"]
                    except Exception as e:
                        errors.append(f"EnumTasks({folder}): {e!s:.80}")
                        return

                    for tn in task_names:
                        name = tn["Data"].rstrip("\x00") if hasattr(tn, "__getitem__") \
                               else str(tn).rstrip("\x00")
                        if not name:
                            continue
                        full_path = folder.rstrip("\\") + "\\" + name
                        try:
                            xml_resp = hSchRpcRetrieveTask(dce, full_path)
                            xml_str  = xml_resp["pXml"]
                            if hasattr(xml_str, "getData"):
                                xml_str = xml_str.getData().decode(
                                    "utf-16-le", errors="replace"
                                )
                            parsed = _parse_task_xml(xml_str)
                            tasks.append({
                                "path":      full_path,
                                "run_as":    parsed["run_as"],
                                "run_level": parsed["run_level"],
                                "actions":   parsed["actions"],
                                "triggers":  parsed["triggers"],
                            })
                        except Exception as e:
                            errors.append(f"RetrieveTask({full_path}): {e!s:.60}")

                # Also try subfolders via EnumFolders
                try:
                    resp    = hSchRpcEnumFolders(dce, "\\", 0, 0, 100)
                    folders = ["\\"] + [
                        "\\" + (f["Data"].rstrip("\x00")
                                if hasattr(f, "__getitem__") else str(f).rstrip("\x00"))
                        for f in resp.get("pNames", [])
                    ]
                except Exception:
                    folders = ["\\"]

                for folder in folders:
                    _enum_folder(folder)

                dce.disconnect()

            except Exception as e:
                logger.warning("scheduled_tasks_enum_connection_error", target=target, error=str(e))
                errors.append(str(e)[:200])

            return {"tasks": tasks, "errors": errors}

        result = await loop.run_in_executor(None, _enum_tasks)
        tasks  = result.get("tasks", [])
        errors = result.get("errors", [])

        # ── Analyse tasks ──────────────────────────────────────────────────

        high_priv_tasks:    list[dict[str, Any]] = []
        writable_path_tasks: list[dict[str, Any]] = []

        for task in tasks:
            run_as = (task.get("run_as") or "").lower()

            # Check if high-privilege principal
            is_high_priv = any(p in run_as for p in _HIGH_PRIV_PATTERNS)

            if is_high_priv:
                # Check each action for potentially writable path
                for action in task.get("actions", []):
                    if action.get("type") != "Exec":
                        continue
                    cmd = (action.get("command") or "").lower()
                    if any(ind in cmd for ind in _USER_WRITABLE_INDICATORS):
                        writable_path_tasks.append({
                            "task":    task["path"],
                            "run_as":  task["run_as"],
                            "command": action.get("command", ""),
                        })
                    else:
                        high_priv_tasks.append({
                            "task":    task["path"],
                            "run_as":  task["run_as"],
                            "command": action.get("command", ""),
                            "args":    action.get("args", ""),
                            "triggers": task.get("triggers", []),
                        })

        # ── Finding 1: High-priv tasks with writable binary paths ─────────
        if writable_path_tasks:
            self.finding(
                title=(
                    f"Scheduled Tasks Running as SYSTEM with Writable Binary Path "
                    f"on {target} ({len(writable_path_tasks)} task(s))"
                ),
                description=(
                    f"{len(writable_path_tasks)} scheduled task(s) on {target} run as "
                    "a high-privilege account AND execute binaries from user-writable "
                    "paths (%TEMP%, %APPDATA%, user directories). "
                    "If the binary path is writable by the current user, "
                    "replacing the binary will execute arbitrary code as SYSTEM "
                    "the next time the task fires."
                ),
                severity=Severity.CRITICAL,
                mitre_technique="T1053.005",
                mitre_tactic="Privilege Escalation",
                evidence={
                    "host":  target,
                    "tasks": writable_path_tasks,
                },
                remediation=(
                    "Move task binaries out of user-writable directories to "
                    "protected system paths (e.g. C:\\Program Files\\). "
                    "Apply icacls to restrict write access on task binary paths. "
                    "Audit scheduled tasks regularly with: "
                    "schtasks /query /fo LIST /v | findstr /i 'task run as'"
                ),
                host=target, confidence=0.85,
            )

        # ── Finding 2: High-priv tasks (informational, for lateral/persistence) ──
        if high_priv_tasks:
            # Report the most interesting ones (limit 15)
            reported = high_priv_tasks[:15]
            self.finding(
                title=(
                    f"High-Privilege Scheduled Tasks Found on {target} "
                    f"({len(high_priv_tasks)} task(s))"
                ),
                description=(
                    f"{len(high_priv_tasks)} scheduled task(s) run as SYSTEM or "
                    "domain admin on {target}. These are candidates for "
                    "persistence (if task ACL is misconfigured) and should be "
                    "reviewed for binary path writability. "
                    "Tasks: "
                    + ", ".join(t["task"] for t in reported)
                    + ("..." if len(high_priv_tasks) > 15 else "")
                ),
                severity=Severity.MEDIUM,
                mitre_technique="T1053.005",
                mitre_tactic="Discovery",
                evidence={
                    "host":         target,
                    "total":        len(high_priv_tasks),
                    "tasks_sample": reported,
                },
                remediation=(
                    "Review the ACL of each task with: "
                    "icacls C:\\Windows\\System32\\Tasks\\<task_name>. "
                    "Ensure only SYSTEM and Administrators have write access. "
                    "Audit task binary paths for writability."
                ),
                host=target, confidence=0.9,
            )

        # ── Finding 3: No tasks found (enumeration info) ───────────────────
        if not tasks and not errors:
            logger.info("scheduled_tasks_none_found", target=target)

        raw = {
            "target":               target,
            "total_tasks":          len(tasks),
            "high_priv_tasks":      high_priv_tasks,
            "writable_path_tasks":  writable_path_tasks,
            "all_tasks":            tasks[:50],  # cap raw output
            "errors":               errors,
        }
        raw["scheduled_tasks"] = self._findings  # OUTPUTS key
        raw["privesc_vectors"] = self._findings  # OUTPUTS key
        return self._findings[:], raw