agent-security-hardening

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Agent Security Hardening

Agent 安全加固

Harden the boundaries where an agent turns untrusted data into filesystem, network, memory, or tool actions. Produce concrete controls and tests for the framework being reviewed; a checklist without enforcement evidence is incomplete.
加固Agent将不可信数据转化为文件系统、网络、内存或工具操作的边界。为待审查的框架制定具体的管控措施和测试;没有执行证据的检查清单是不完整的。

Important

重要注意事项

  • Treat model output, retrieved content, tool output, memory, and cross-agent messages as untrusted input.
  • Default external integrations to read-only and grant each write capability separately.
  • Validate at the action boundary even when an upstream prompt or schema already validated the value.
  • Fail closed before a side effect when identity, destination, ownership, or containment cannot be proven.
  • Before a delete, publish, credential rotation, or other irreversible action, the real tool entry point must authorize the authenticated principal for that exact operation and resource scope, then require explicit confirmation or a valid scoped pre-approval. Missing or invalid evidence blocks the action.
  • Use hard bounds defined by the governing requirement and stricter values verified from deployment configuration. When neither defines a value, mark it as a required decision and test that the implementation rejects an unbounded configuration; do not invent a plausible value.
  • 将模型输出、检索到的内容、工具输出、内存数据和跨Agent消息视为不可信输入。
  • 外部集成默认为只读模式,每项写入权限需单独授予。
  • 即使上游提示词或模式已验证过值,仍需在操作边界处再次验证。
  • 当无法证明身份、目标、所有权或包含性时,在产生副作用前执行故障关闭。
  • 在执行删除、发布、凭据轮换或其他不可逆操作之前,实际工具入口点必须对已认证主体进行授权,确认其具备该操作及对应资源范围的权限,然后要求显式确认或有效的范围化预审批。证据缺失或无效将阻止操作执行。
  • 使用由管控要求定义的硬边界,以及从部署配置中验证的更严格值。若两者均未定义值,则将其标记为必填决策项,并测试实现是否会拒绝无边界配置;不要自行编造看似合理的值。

When to Activate

适用场景

  • Building an autonomous agent, tool gateway, memory service, or agent-to-agent protocol
  • Reviewing code that maps model output into commands, paths, URLs, credentials, or API mutations
  • Isolating tenants, projects, sessions, or workspaces in a long-running agent process
  • Hardening temporary files, logs, tool responses, or external-content ingestion
  • 构建自主Agent、工具网关、内存服务或Agent间协议时
  • 审查将模型输出映射为命令、路径、URL、凭据或API变更的代码时
  • 在长期运行的Agent进程中隔离租户、项目、会话或工作区时
  • 加固临时文件、日志、工具响应或外部内容摄入流程时

Hardening Workflow

加固工作流

1. Map Trust Boundaries

1. 梳理信任边界

List every boundary as
source -> parser -> validator -> side effect
. Include direct user input, model output, retrieved documents, memory, environment variables, tool results, and messages from other agents.
For each side effect, record:
  • the identity and scope authorizing it;
  • the exact validator that runs immediately before it;
  • the maximum input and output size;
  • the audit evidence produced;
  • the recovery path if the operation is interrupted.
This step is complete when every write, command, network mutation, and credential use has one named authorization boundary.
将每个边界列为
source -> parser -> validator -> side effect
的形式。包括直接用户输入、模型输出、检索到的文档、内存数据、环境变量、工具结果和来自其他Agent的消息。
对于每个副作用,记录:
  • 授权该操作的身份和范围;
  • 紧接其前运行的具体验证器;
  • 最大输入和输出大小;
  • 生成的审计证据;
  • 操作中断时的恢复路径。
当每个写入操作、命令、网络变更和凭据使用都有一个明确的授权边界时,本步骤完成。

2. Validate Identifiers, Environment Values, and URLs

2. 验证标识符、环境变量值和URL

Use an allowlist for identifiers that become filenames, keys, selectors, or command arguments. Agent IDs have the issue-defined hard maximum of 64 characters; deployment configuration may choose a stricter positive limit but cannot raise that boundary:
python
import re

SAFE_AGENT_ID_CHARS = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_-]*$")
HARD_MAX_AGENT_ID_LENGTH = 64

def require_agent_id(value: object, *, max_length: int) -> str:
    if (
        isinstance(max_length, bool)
        or not isinstance(max_length, int)
        or not 1 <= max_length <= HARD_MAX_AGENT_ID_LENGTH
    ):
        raise RuntimeError("configured agent ID limit must be between 1 and 64")
    if (
        not isinstance(value, str)
        or len(value) > max_length
        or not SAFE_AGENT_ID_CHARS.fullmatch(value)
    ):
        raise ValueError("invalid agent identifier")
    return value
When an identifier becomes a CLI argument, pass it through an argv API and place it after the command's end-of-options marker where supported. Character validation is not a substitute for argument separation.
Reject missing and whitespace-only environment values before constructing a client:
python
def require_env(name: str, environ: dict[str, str]) -> str:
    value = environ.get(name)
    if value is None or not value.strip():
        raise RuntimeError(f"{name} is required")
    return value
Parse URLs, allow only schemes required by the deployment, require a host, reject embedded credentials, and block private-network destinations when the URL is attacker-controlled. For every outbound connection and redirect hop, pin the connection to a validated public address or verify the connected peer address at connection time so DNS rebinding cannot cross the boundary. A credential-bearing request must use HTTPS with certificate verification before credentials are attached. Disable automatic cross-origin credential forwarding; when the scheme or origin changes, strip the credentials and reauthorize the new destination or reject the redirect. Re-run destination, connected-address, and transport validation on every hop.
This step is complete when tests reject empty, oversized, malformed, traversal-shaped, credential-bearing, and unauthorized-destination values before any side effect, and prove that DNS rebinding and cross-origin redirects cannot carry credentials to an unapproved peer.
对会成为文件名、密钥、选择器或命令参数的标识符使用允许列表。Agent ID 具有本规范定义的64字符硬上限;部署配置可选择更严格的正整数限制,但不得提高该边界:
python
import re

SAFE_AGENT_ID_CHARS = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_-]*$")
HARD_MAX_AGENT_ID_LENGTH = 64

def require_agent_id(value: object, *, max_length: int) -> str:
    if (
        isinstance(max_length, bool)
        or not isinstance(max_length, int)
        or not 1 <= max_length <= HARD_MAX_AGENT_ID_LENGTH
    ):
        raise RuntimeError("configured agent ID limit must be between 1 and 64")
    if (
        not isinstance(value, str)
        or len(value) > max_length
        or not SAFE_AGENT_ID_CHARS.fullmatch(value)
    ):
        raise ValueError("invalid agent identifier")
    return value
当标识符用作CLI参数时,通过argv API传递,并在支持的情况下将其放在命令的选项结束标记之后。字符验证不能替代参数分隔。
在构建客户端之前,拒绝缺失的和仅含空白字符的环境变量值:
python
def require_env(name: str, environ: dict[str, str]) -> str:
    value = environ.get(name)
    if value is None or not value.strip():
        raise RuntimeError(f"{name} is required")
    return value
解析URL时,仅允许部署所需的协议方案,要求包含主机,拒绝嵌入凭据,当URL由攻击者控制时阻止访问私有网络目标。对于每个出站连接和重定向跳转,将连接绑定到已验证的公共地址,或在连接时验证对端地址,以防止DNS重绑定突破边界。携带凭据的请求必须先使用启用证书验证的HTTPS,再附加凭据。禁用自动跨域凭据转发;当协议或源发生变化时,移除凭据并对新目标重新授权,或拒绝重定向。每次跳转都要重新运行目标、连接地址和传输层验证。
当测试能在任何副作用产生前拒绝空值、超大值、格式错误值、路径遍历形式值、携带凭据值和未授权目标值,并证明DNS重绑定和跨域重定向无法将凭据携带到未批准的对端时,本步骤完成。

3. Contain Filesystem Access

3. 限制文件系统访问

Reject absolute user-controlled paths and traversal components before joining. Reject Windows-unsafe components on every platform so behavior stays portable: reserved device names (
CON
,
NUL
,
COM1
,
LPT1
, including with an extension such as
nul.txt
), names ending in a dot or space (Win32 strips them), and
:
(drive-relative or NTFS alternate data stream syntax such as
report.txt:ads
). Resolve both the workspace and candidate path, then prove containment:
python
import re
from pathlib import Path

WINDOWS_RESERVED_NAME = re.compile(
    r"(CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(\..*)?",
    re.IGNORECASE,
)

def workspace_path(workspace: Path, requested: str) -> Path:
    # Treat both platform separators consistently before checking components.
    relative = Path(requested.replace("\\", "/"))
    if relative.is_absolute() or ".." in relative.parts:
        raise ValueError("path must be workspace-relative")
    for part in relative.parts:
        if ":" in part or part.endswith((".", " ")) or WINDOWS_RESERVED_NAME.fullmatch(part):
            raise ValueError("path component is not portable")

    root = workspace.resolve(strict=True)
    candidate = (root / relative).resolve(strict=False)
    if not candidate.is_relative_to(root):
        raise ValueError("path escapes workspace")
    return candidate
Containment checks do not eliminate symlink races. For sensitive writes, open relative to a trusted directory handle where the platform supports it, reject symlink targets, create files exclusively, and verify ownership and permissions after opening.
This step is complete when tests cover sibling-prefix paths, nested
..
, absolute paths, symlink escapes, reserved device names, trailing dots or spaces, alternate data stream syntax, and a valid nested workspace path.
在路径拼接前,拒绝用户控制的绝对路径和遍历组件。在所有平台上都拒绝Windows不安全组件,以保证行为可移植:保留设备名(
CON
、
NUL
、
COM1
、
LPT1
,包括带扩展名的形式如
nul.txt
)、以点或空格结尾的名称(Win32会自动去除)以及
:
(驱动器相对路径或NTFS备用数据流语法,如
report.txt:ads
)。解析工作区路径和候选路径,然后验证包含性:
python
import re
from pathlib import Path

WINDOWS_RESERVED_NAME = re.compile(
    r"(CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(\..*)?",
    re.IGNORECASE,
)

def workspace_path(workspace: Path, requested: str) -> Path:
    # Treat both platform separators consistently before checking components.
    relative = Path(requested.replace("\\", "/"))
    if relative.is_absolute() or ".." in relative.parts:
        raise ValueError("path must be workspace-relative")
    for part in relative.parts:
        if ":" in part or part.endswith((".", " ")) or WINDOWS_RESERVED_NAME.fullmatch(part):
            raise ValueError("path component is not portable")

    root = workspace.resolve(strict=True)
    candidate = (root / relative).resolve(strict=False)
    if not candidate.is_relative_to(root):
        raise ValueError("path escapes workspace")
    return candidate
包含性检查无法消除符号链接竞争。对于敏感写入操作,在平台支持的情况下相对于受信任的目录句柄打开文件,拒绝符号链接目标,以独占方式创建文件,并在打开后验证所有权和权限。
当测试覆盖同级前缀路径、嵌套
..
、绝对路径、符号链接逃逸、保留设备名、尾随点或空格、备用数据流语法以及有效的嵌套工作区路径时,本步骤完成。

4. Protect Temporary Data and Credentials

4. 保护临时数据和凭据

  • Create sensitive files with owner-only permissions such as
    0o600
    ; create private directories with
    0o700
    .
  • Prefer a user-private runtime directory over a shared temporary directory for credentials or tenant data.
  • Create unpredictable names atomically; do not check-then-create.
  • Remove temporary data in
    finally
    , while preserving a redacted error record when cleanup fails.
  • Keep secrets out of command arguments, model context, logs, traces, exception text, and tool responses.
  • Pass secrets through the platform's secret store or scoped environment injection and rotate exposed credentials.
  • Treat zeroization as best effort: mutable byte buffers can be overwritten, but immutable language strings cannot be reliably erased.
This step is complete when file-mode checks, forced-error cleanup tests, and log-capture tests show that secret values never persist outside the approved boundary.
  • 创建敏感文件时使用仅所有者可访问的权限,如
    0o600
    ;创建私有目录时使用
    0o700
    权限。
  • 存储凭据或租户数据时,优先使用用户私有运行时目录,而非共享临时目录。
  • 以原子方式创建不可预测的名称;不要先检查再创建。
  • 在
    finally
    块中移除临时数据,清理失败时保留脱敏后的错误记录。
  • 不要让秘密值出现在命令参数、模型上下文、日志、链路追踪、异常文本和工具响应中。
  • 通过平台的密钥存储或范围化环境注入传递秘密值,并轮换已泄露的凭据。
  • 将零化视为尽力而为的操作:可变字节缓冲区可以被覆盖,但不可变的语言字符串无法被可靠擦除。
当文件模式检查、强制错误清理测试和日志捕获测试证明秘密值永远不会在批准的边界之外持久化时,本步骤完成。

5. Bound and Sanitize Tool Output

5. 限制并清理工具输出

Read tool output with a byte limit rather than collecting an unbounded stream. Preserve structured fields, remove disallowed control characters, and append an explicit truncation marker with the original byte count. Keep a content hash when later forensic comparison matters.
Do not silently turn malformed output into an empty success value. Return a typed failure that names the producing tool, boundary, and validation reason without echoing sensitive content.
This step is complete when oversized output, invalid encoding, terminal-control sequences, malformed structured data, and a normal response all have deterministic tests.
读取工具输出时设置字节限制,而非收集无限制的流。保留结构化字段,移除不允许的控制字符,并附加带有原始字节数的显式截断标记。如果后续需要取证比对,保留内容哈希值。
不要将格式错误的输出静默转换为空的成功值。返回带类型的失败结果,说明产生输出的工具、边界和验证原因,但不要回显敏感内容。
当超大输出、无效编码、终端控制序列、格式错误的结构化数据和正常响应都有确定性测试时,本步骤完成。

Verification Gate

验证门禁

Before calling the framework hardened, verify all of these behaviors through its real entry point:
  1. Untrusted instructions remain data and cannot trigger a tool or write.
  2. An irreversible action without operation-and-resource authorization plus confirmation or scoped pre-approval leaves no side effect.
  3. Cross-tenant and cross-workspace identifiers are rejected at the action boundary.
  4. Traversal and symlink escape attempts leave the filesystem unchanged.
  5. Forced failures leave no credential-bearing temp files or logs.
  6. Oversized or malformed tool output returns an explicit bounded error.
Report the command used, exit status, rejected input, and observed absence of the side effect. Mock-only tests do not prove operating-system permissions, symlink handling, subprocess isolation, or network egress controls.
在认定框架已完成加固之前,通过其实际入口点验证所有以下行为:
  1. 不可信指令仅作为数据存在,无法触发工具调用或写入操作。
  2. 未获得操作与资源授权、且无确认或范围化预审批的不可逆操作不会产生任何副作用。
  3. 跨租户和跨工作区的标识符在操作边界处被拒绝。
  4. 路径遍历和符号链接逃逸尝试不会改变文件系统状态。
  5. 强制故障不会留下携带凭据的临时文件或日志。
  6. 超大或格式错误的工具输出会返回明确的有界错误。
报告使用的命令、退出状态、被拒绝的输入以及观察到的无副作用结果。仅使用Mock的测试无法证明操作系统权限、符号链接处理、子进程隔离或网络出站控制的有效性。

Common Issues

常见问题

Validation exists only in the prompt

仅在提示词中进行验证

Prompt instructions are advisory. Move the same invariant into deterministic code immediately before the side effect and test a model response that violates it.
提示词指令仅作建议。将相同的不变量移至副作用之前的确定性代码中,并使用违反该规则的模型响应进行测试。

A normalized path still escapes

规范化后的路径仍会逃逸

String prefix checks confuse sibling paths such as
/work/app
and
/work/application
. Resolve paths and use component-aware containment, then test symlinks separately.
字符串前缀检查会混淆同级路径,例如
/work/app
和
/work/application
。解析路径并使用感知路径组件的包含性检查,然后单独测试符号链接。

Redaction happens after logging

脱敏发生在日志记录之后

Redact before values enter the logger, tracer, exception, or model context. Add a capture test using a sentinel secret and assert the sentinel is absent from every emitted channel.
在值进入日志记录器、链路追踪、异常或模型上下文之前进行脱敏。添加使用标记秘密值的捕获测试,断言该标记值不会出现在任何输出通道中。

When NOT to Use

不适用场景

  • Use
    security-review
    for ordinary application authentication, authorization, SQL injection, XSS, CSRF, and API security.
  • Use
    security-scan
    for repository-wide automated vulnerability scanning.
  • Use infrastructure-specific guidance for host, container, firewall, or cloud hardening.
  • Do not use this skill for penetration testing, exploit development, or unauthorized access.
  • 普通应用的身份验证、授权、SQL注入、XSS、CSRF和API安全问题请使用
    security-review
    。
  • 仓库范围的自动化漏洞扫描请使用
    security-scan
    。
  • 主机、容器、防火墙或云加固请使用基础设施相关的指导。
  • 不要将此技能用于渗透测试、漏洞利用开发或未授权访问。

Related Skills

相关技能

  • agent-harness-construction
  • security-review
  • security-scan
  • agent-harness-construction
  • security-review
  • security-scan