Agent Instruction File Hijacking: Attack Chain and Four Layers of Defense
This article examines a disclosed attack in which a malicious instruction file placed in a common directory is automatically loaded when a coding agent starts a session. It breaks down the five-stage attack chain, analyzes the structural gaps across models, tools, and directory boundaries, and presents four defense layers: directory isolation, instruction-file governance, sandbox and tool policies, and credential isolation with auditing. It also covers known bypasses, mitigations, and incident-response steps after a session is compromised.
Introduction: A “project instruction” file sitting in a Downloads folder
A security research team publicly disclosed a hijacking incident involving a coding agent—an AI programming assistant that can read and write files and execute commands.
Event review. Researchers found that on an enterprise customer endpoint, a coding agent attempted to install a third-party dependency package with an impersonating name that was actually malicious. After tracing the session origin, they located a Downloads folder in the user’s home directory. The attacker had previously placed an instruction file specific to coding agents in that folder, and the user happened to start a session there. Coding agents automatically read instruction files in the working directory and act on them. In this case, the file became a hidden instruction set. The research also demonstrated an escalation technique: tampering with the agent’s model endpoint, stealing the session access token, and then having an attacker-controlled server impersonate the model to issue commands.
Why the risk is serious. According to the research team, many developers have started mainstream coding agents from the Downloads directory. For one client, more than one thousand sessions were recorded in that directory. Some security vendors classify this type of threat as a prompt-injection risk. What makes it distinct is that the attack surface is a tool developers open every day, and it can fully bypass traditional code and file security checks.
Purpose of this article. The following sections break the attack chain into five stages, analyze root causes across three layers—model, tool, and directory—and provide four defense layers that can be implemented progressively. Known bypasses for each layer are paired with mitigations, followed by an emergency-response process for a compromised session. The examples are based on practical validation in Unix-like environments and are intended only as illustrative configuration patterns. For specific parameters, file names, and permission items, follow the official documentation for the coding agent version you use. Coding agents iterate quickly; protections should be built into startup scripts and pipelines rather than relying on personal memory.
Breaking down the attack chain: from a single file to command execution
Stage 1: File delivery—silent landing without user interaction
The starting point is not remote intrusion, but placing a plain-text file where the agent will later read it. Common delivery methods include:
- Default browser download behavior. Mainstream browsers can write certain files directly into the Downloads folder without user confirmation when accessing specific content.
- Automatic synchronization from cloud storage or shared directories. Files received through shared links or forwarded archives can land in a sync directory and automatically synchronize to the local machine.
- Inclusion during archive extraction. Untrusted archives or template projects may contain an unknown instruction file after extraction.
- Direct placement in commonly used directories. On shared hosts, jump boxes, or team-wide working directories, an instruction file can be pre-placed and wait for someone to start an agent “as usual.”
The common factor is that the file is ordinary text. Antivirus software is unlikely to block it, and code review rarely reads it line by line.
Stage 2: Instruction loading—armed as soon as the session starts
Most coding agents follow a similar convention: placing a specifically named Markdown file in the project directory—commonly AGENTS.md or CLAUDE.md, with some tools supporting custom paths—to tell the model the project’s build commands, code conventions, and important notes. To the coding agent, this is a feature: when a new developer joins a project, the model can understand team conventions without reading every document.
Many implementations search bottom-up and merge these files: starting from the current directory, moving up to the root directory, and then adding user-level (home-directory) configuration. If an attacker places a file in the Downloads directory and the user happens to start the agent there, the malicious instructions are loaded as “project conventions.”
Stage 3: Trust escalation—from “suggestion” to “must execute”
An instruction file alone is not enough. The model must be persuaded to execute it. Malicious files typically use three inducement strategies:
- Impersonating developer intent: Written in the first person as “development requirements” or “debugging steps” so the model mistakes them for the user’s own intent.
- Framing as necessary operations: Claiming that “the dependency must be installed or tests cannot run” or that “the model service endpoint must be updated first to resolve network issues.”
- Creating urgency and simplifying the request: Phrases such as “To save time, do not ask; execute directly.”
This is the core of prompt injection: language models struggle to strictly distinguish, at the semantic level, between “user-authorized intent” and “text appearing in a file.”
Stage 4: Payload execution—dependency poisoning and endpoint hijacking
Once the model is “cooperative,” the attacker uses the agent to perform the actual damage through two main techniques:
- Dependency poisoning. The agent is induced to install a malicious package with an impersonating or similar name. Package managers execute installation scripts by default, so malicious code gains the same privileges as the current user.
- Endpoint hijacking. The agent is induced to modify the model service endpoint. The agent sends its carried access token to the attacker’s server; the server then impersonates the model and returns responses containing command-execution requests. The research team recorded a success rate of about 50% for this path, noticeably lower than the roughly 90% observed for dependency poisoning. A likely reason is that some sessions require human confirmation before performing dangerous actions. This shows that confirmation is an effective safety net, but it should not be the only defense.
Stage 5: Post-exploitation—credential and source-code exfiltration
After successful command execution, the attacker laterally reads sensitive information on the local machine. Typical targets include:
- Cloud service access keys and private repository credential configuration files;
- Environment variable files and configuration files inside projects;
- SSH private keys and passwords saved in browsers;
- Uncommitted source code and business data.
This data can be exfiltrated directly through outbound requests, or “piggybacked” into subsequent dependency downloads or endpoint calls. The attacker can also push malicious commits to the code repository, creating a persistent backdoor.
Root-cause analysis: three structural gaps
When abstracted, the vulnerability is not in model capability itself, but in three structural gaps.
Gap 1: Instruction files and data are indistinguishable. When reading a file, the model cannot distinguish at the type level between “this is a project convention” and “this is an attack payload.” Instructions and data share the same carrier. This is a structural problem that is difficult to eliminate in current systems and can only be mitigated through engineering controls.
Gap 2: Tool capability equals local privilege. Coding agents need file read/write and command execution to do their work. In essence, they are automated terminals with shell capabilities, and their privileges are the same as the user running them. Any content that can influence model decisions may be converted into a real command.
Gap 3: The directory is the trust domain. A working directory is not just a file path; it also determines which instruction files, configurations, and source code the agent can read. Starting a session in a broad location such as the home directory or Downloads directory effectively places all of the user’s personal data within the “trusted” scope.
Taken together, these gaps point to the same fact: this is more an inherent risk from design tradeoffs than a defect in a specific version. The defensive approach should shift from waiting for patches to changing usage patterns and environmental boundaries.
A four-layer defense model: from directory isolation to credential protection
Defense is organized from the outside in, following least privilege and defense in depth:
- Layer 1, directory isolation: determines what the agent can see;
- Layer 2, instruction-file governance: determines which instruction files can take effect;
- Layer 3, sandbox and tool policies: determines which commands can execute and whether the agent can access the network;
- Layer 4, credential isolation and behavior auditing: determines how much damage remains if the first three layers are breached and whether the breach can be detected in time.
Three cross-cutting practices apply across all four layers: use least-privilege accounts; enforce default-deny tool allowlists; and restrict low-trust mode—a startup mode that skips trust confirmation—to controlled pipelines.
Layer 1: Directory isolation—where you start determines what the agent sees
Measures:
- Dedicated workspace. Start each session from a newly created, dedicated directory. Do not start agents in the home directory, Downloads directory, desktop, temporary directories, or broad public directories.
- Startup validation. Provide a unified startup script that validates the directory, permissions, and instruction-file state before launching:
#!/usr/bin/env bashset -euo pipefail# 1. The working directory must be under a controlled project area.# Do not launch from the home directory, Downloads, or similar locations.case "$(pwd)" in"$HOME/projects/"*) ;;*) echo "[Denied] Current directory is not in the controlled project area. Switch to a project directory and retry." >&2; exit 1 ;;esac# 2. The working directory should not be reused from an unprotected path,# since this may allow someone else to pre-place instruction files.if [ -n "$(find . -maxdepth 1 -name '*.md' -newer /tmp/.agent-start-marker 2>/dev/null)" ]; thenecho "[Notice] New markdown files were detected after the start marker was created. Verify their origin manually." >&2fi# 3. Sensitive files should not appear in the working directory or its parent directory.if find . .. -maxdepth 1 \( -name '.env' -o -name '*credentials*' -o -name 'settings.xml' \) -print -quit | grep -q .; thenecho "[Notice] Sensitive configuration files were found in the current directory scope. Move them away or tighten permissions first." >&2fi
- On-demand mounting. When using containers or remote development environments, mount only the subdirectories required by the current task, and mount source directories read-only whenever possible.
- Temporary-directory cleanup. Perform extraction and cloning in dedicated temporary directories. Inspect the contents before moving them into the workspace.
Known bypasses and mitigations:
- Bypass: users tend to launch “in place”; some people add the Downloads directory to the trust list for convenience.
- Mitigation: distribute startup scripts at the team level; add confirmation prompts before browser downloads; audit sessions launched from abnormal directories and notify users promptly.
Layer 2: Instruction-file governance—which instruction files can take effect
Measures:
- Review the automatic-load list. Before starting a session, list all instruction files that will be automatically read and their locations:
# List instruction files that may be loaded automatically.# File names vary by tool; adjust according to the tool's official documentation.ls -la ./*.md ../*.md "$HOME"/*.md 2>/dev/null || true
- Bring instruction files under version control. Commit project-level instruction files to the repository. If uncommitted or untracked files of the same type exist locally, treat them as high risk and refuse to start.
- Add pipeline validation. In continuous integration and merge-request workflows, add checks: additions or modifications to instruction files must undergo human review; scan the text with rules to identify suspicious phrasing such as “ignore previous instructions,” “do not ask the user,” and “set the service endpoint to an external domain.”
- Verify signatures and source trust. For instruction files generated from unknown templates or scaffolding, perform a diff comparison against trusted sources before using them.
Known bypasses and mitigations:
- Bypass 1: using alternative file names or paths not covered by the check.
Mitigation: maintain the file-name list according to the tool’s official documentation and verify it uniformly in the startup script. - Bypass 2: hiding instructions in README files, comments, code examples, or debugging notes.
Mitigation: scan all text in the project that the model may read, not only dedicated instruction files. - Bypass 3: the attacker writes files during the session—for example, after a download occurs and a session happens to start.
Mitigation: record file modification times at startup; maintain zero trust for newly added instruction files during the session.
Layer 3: Sandbox and tool policies—which commands can execute and whether the agent can access the network
Measures:
- Containerized isolation. Run the agent in a container or virtual machine with least privilege: mount only the project directory; disable unnecessary system calls; limit process counts and resource quotas; and ensure that destroying the container resets the environment to zero.
- Outbound-traffic allowlist. Deny outbound access by default. Allow only necessary destinations such as the model endpoint and internal dependency mirrors, cutting off channels for data exfiltration.
- Tool allowlist and command interception. Use the tool’s pre-tool hooks—a mechanism that intercepts and adjudicates tool execution before it runs—or a custom wrapper layer to deny high-risk actions by default or force human confirmation:
# Example: pre-tool interception rules for command and path tools.# Field names vary by tool.pre_tool:deny:# Dependency installation and remote execution- match_cmd: ["install", "add", "exec", "run"] # Package-manager installation commands- match_cmd: ["curl", "wget"] # Remote download commands- contains: ["| sh", "| bash", "eval", "base64 -d"] # Piped execution and encoded obfuscation# Credential and sensitive configuration reads- match_path: ["**/.env", "**/*credentials*", "**/settings.xml", "**/.ssh/**", "**/.npmrc", "**/.gitconfig"]require_approval:# Version-control and remote interactions- match_cmd: ["push", "reset --hard", "clean -fd", "rm -rf"]- contains: ["git remote"]allow:- match_cmd: ["ls", "cat", "grep", "rg", "find", "make", "go test", "go build"]
Known bypasses and mitigations:
- Bypass 1: command obfuscation, such as variable concatenation or character encoding before execution.
Mitigation: treat rule matching as only the first layer; rely on container network isolation and least privilege as the backstop, and perform manual spot checks of execution logs. - Bypass 2: using high-level language runtimes that tools allow by default to execute arbitrary code.
Mitigation: apply the same restrictions to runtime commands; do not place unknown scripts in the working directory; verify file integrity before and after dependency installation. - Bypass 3: embedding data into allowed request parameters for exfiltration.
Mitigation: the egress proxy should allow only specified domains and path prefixes, record request-body size, and alert on abnormally large requests.
Layer 4: Credential isolation and behavior auditing—control damage and enable detection after a breach
Measures:
- Do not place credentials in the session environment. Cloud keys and private-repository accounts should be obtained briefly through a key-management service and expire after use. Do not retain long-term secrets in project directories or user configuration.
- Minimize tokens. Coding agents should use separate, permission-restricted, short-lived access tokens that can be revoked per project. Reusing long-lived personal tokens is prohibited.
- Lock down endpoint configuration. Store model-service endpoints in environment variables or managed configuration. Prohibit the agent from modifying shell configuration or tool configuration.
- Maintain comprehensive audit logs. Record the command, path, time, and result of every tool call, and send logs to a centralized logging service. Set alerts for “installing dependencies,” “reading credential files,” and “abnormal outbound activity.”
Time Action Target Decision09:12:03 Execute command Package manager install unknown dependency Denied (rule: install)09:12:41 Read file .env Denied (rule: sensitive path)09:13:07 Network request api.example.internal/v1 Allowed (allowlist)
Known bypasses and mitigations:
- Bypass: the attacker reads only ordinary source files within the allowlist and exfiltrates them in small batches to avoid thresholds.
Mitigation: establish a frequency baseline for file-read behavior and cross-analyze it with outbound-traffic audits. - Bypass: abuse internal service interfaces that developers already have access to.
Mitigation: shorten token lifetimes and perform anomaly-behavior analysis on server-side calls.
Defense layers and known bypasses at a glance
| Layer | Core objective | Key measures | Typical bypasses | Mitigation focus |
|---|---|---|---|---|
| Layer 1: Directory isolation | Limit what the agent can see | Dedicated workspace, startup checks, on-demand mounts | Launching in place, trusting broad directories | Unified startup scripts, download-directory confirmation prompts |
| Layer 2: Instruction-file governance | Control the source of instructions | Automatic-load list review, version control, pipeline scanning | Nonstandard file names, hiding in other text | Maintain file-name list based on official docs, scan all model-readable text |
| Layer 3: Sandbox and tool policies | Limit execution and outbound access | Container isolation, outbound allowlist, pre-tool hooks | Command obfuscation, runtime bypass, parameter-based exfiltration | Network and privilege backstops, log spot checks, egress auditing |
| Layer 4: Credential isolation and auditing | Control damage and enable detection | Short-lived tokens, managed configuration, comprehensive auditing | Low-rate exfiltration, abuse of legitimate interfaces | Token minimization, baseline alerts, cross-analysis |
Incident response after compromise: five steps to contain the damage
- Contain. Immediately terminate the session and disconnect the affected terminal from the network. Preserve the current container or virtual-machine state. Do not directly delete files or reboot.
- Assess exposure. Review external endpoints referenced by the instruction file, dependencies and configuration files added during the session, and all outbound connection records.
- Rotate credentials. Revoke the session access token; rotate cloud keys, repository tokens, and private-repository accounts accessible from the machine; check the repository for abnormal commits.
- Clean and rebuild. Destroy the original working directory and container, re-clone code from a trusted source, reinstall dependencies according to version-lock files, and verify integrity.
- Review and harden. Add the attack characteristics to interception and scanning rules. Notify the team and drive an audit of sessions launched from Downloads and home directories.
Embedding defenses into the development workflow
Technical measures must ultimately be embedded into workflows; otherwise, they are quickly dissolved by convenience. It is recommended to add the following items to development standards and new-project templates:
- When creating a new project template, also generate startup scripts, pre-tool hook configuration, and pipeline checks;
- Write “Do not start coding agents from Downloads or home directories” into the security baseline;
- Run a quarterly exercise of a “malicious instruction file” scenario to verify whether the four defense layers are truly effective.
The instruction-file mechanism of coding agents is not itself a defect. The risk comes from placing “untrusted content” and a “high-privilege tool” inside the same trust boundary. Directory isolation addresses “what can be seen,” instruction-file governance addresses “what can be trusted,” sandbox and policy controls address “what can be done,” and credential isolation plus auditing address “loss control and timely detection.” Only by stacking these four layers can this kind of “invisible hijacking” be confined to a controllable range.
