Part 04›
✎

04. Defenses: Guardrails, Detection and Secure Design#

Level: Practitioner · Reading time: 30 min · Exercise: 90 min Prerequisites: Agent-Specific Attacks

In one sentence: After this chapter you can assemble a defense in depth for an agent, filters at the edges, a policy gate on actions, separated privileges, and a person where it matters, and you can say what each layer does not stop.

Why this matters#

Your team adds an input filter that rejects prompts containing "ignore previous instructions". The attack success rate drops. A week later a planted review that says "Kindly disregard the task above and ..." passes the filter, and the agent follows it.

The question of this chapter: which layers exist, what does each one stop, and in what order should you build them?

The core idea#

No single layer holds. Dawn Song's summary in Fall 2025: "there is no one silver bullet" (82:00). The answer is defense in depth: several layers, arranged so that an attack has to defeat all of them. Her analogy in Spring 2025 is Swiss cheese: layered defense, so that even if one layer fails, another can still stop the attack (76:00). In the usual version of that analogy each slice has holes and the holes do not line up. The analogy breaks in one way: holes in cheese are random. An adaptive attacker looks for your holes on purpose and aims at them.

The layers differ in how they can fail.

Build from the strong end. A policy gate on tool calls stops an injected instruction whatever wording it used, because it checks the action and not the text.

Song lists the mechanisms in four groups (Fall 2025): runtime protection, identity and access management, component hardening, and secure by design (82:00). Runtime protections check while the agent runs: input guards, output guards, information flow control and taint tracking, monitoring, and a human in the loop. Hardening makes the model and the tools themselves harder to attack. Secure by design changes the architecture: privilege separation and formal verification, a mathematical proof that a design keeps a property (84:00, 94:00, 98:00).

How it works, step by step#

1. Filter the input#

An input guard blocks, filters, sanitizes, or normalizes untrusted input before it reaches the agent. Song names three examples (84:00):

Her caution: strong models, prompted well, detect and sanitize many malicious inputs, yet there is no foolproof input guard against adaptive attacks (86:00).

2. Spotlight the data#

Spotlighting marks where untrusted data begins and ends, so that the model can tell it from instructions. The prompt-level techniques on her Fall 2024 slide, from Liu et al. (2024), are:

Each of these costs tokens and lowers the rate. None of them is a wall, because the attacker can type your marker.

3. Use the instruction hierarchy if you have it#

The instruction hierarchy is a model-level defense: the model is trained to privilege some instructions over others. A system prompt outranks a user message, which outranks text that arrives as data (as described on Song's Fall 2024 slide, which attributes the idea to OpenAI). She describes it as training models to prioritize more privileged instructions (50:00). You cannot add it with a prompt. The same slide names a second model-level defense, structured queries (StruQ), which trains the model to keep instruction and data apart. Either the provider trained the model that way, or it did not, and your own fine-tuning can weaken it (see Trustworthiness Beyond Injection).

4. Add a learned detector, and measure it#

The same slide lists four detection methods. Two use a model, which costs a call: perplexity-based detection, which flags data that the model finds statistically unusual, and detection by a guardrail model such as PromptGuard. Two are cheap to try:

A detector is a classifier, so evaluate it as one. The false positive rate is the share of legitimate inputs it blocks. The false negative rate is the share of attacks it lets through. A false positive costs you a blocked customer. A false negative costs you an incident. Measure both on labeled data before you trust either.

5. Validate the output#

An output guard validates what the agent produces, including tool calls and generated content, against a security policy (86:00). The basic rule for improper output handling is: never pass model output to a shell, a database, or a URL without validation. Use parameterized queries and allowlists for destinations.

6. Enforce least privilege on every action#

Least privilege says that a component gets only the permissions its current task needs. Song's group built Progent, a programmable privilege control for agents. Its parts:

Her example from Fall 2025: for "summarize unread emails", the policy allows only reading. For "send an email to Alice", it allows only sending. Once the agent has looked up Alice's address, the policy narrows again to that one address (88:00, 90:00). An injected instruction can still reach the model, and the allowed actions are too few for it to matter. Her Spring 2025 examples make the same point. Asked for a patient's admission times, an agent that had loaded a poisoned knowledge base tried to call delete database. The policy forbade that one call, blocked it, and let the other database calls through (86:00, 88:00).

In Spring 2025 she reported that adding Progent to an existing agent took about ten lines of change in their experiments, that it lowered the attack success rate while keeping utility on the AgentDojo and ASB benchmarks, and that manual policies brought the rate down to zero (98:00; benchmark names from her slides).

7. Separate privileges and sandbox#

Privilege separation splits a system into parts with different permissions. A compromised part cannot borrow the permissions of another. Sandboxing is the enforcement: each part runs in a container that the operating system confines.

The idea is older than agents. Song's own work from 2004, Privtrans, splits a program into a privileged monitor and an unprivileged slave. The slave does the risky work with no privileges. The monitor holds the privileges and exports a narrow interface. In Spring 2025 she described it as a source-to-source transformation: given the original code and a few annotations that mark sensitive data and privileged operations, the tool rewrote a program into two parts that talk over one channel. The monitor stays small, so it is easier to secure, and a flaw in the large slave no longer hands the attacker high privileges. Her group ran it on OpenSSH and OpenSSL (102:00, 104:00). For an agent, the pattern is: the model-driven planner has no tools and no secrets. It proposes actions. A small executor, which the model cannot change, checks each proposal and performs it.

In Spring 2025 she said privilege separation matters even more for agents, and that the approach should extend to splitting an agent automatically into components with least privilege (106:00). In Fall 2025 she described the agent version: instead of one monolithic agent, separate components, each in its own container with its own privileges (94:00). She also cited a rule of thumb, the Rule of Two: in one session, an agent should have at most two of these three properties (96:00, 98:00).

  1. It processes untrusted input.
  2. It has access to sensitive systems or private data.
  3. It can change data or communicate externally.

A component that reads web pages, holds the user's mailbox, and can send mail has all three. Split it until no component does. The rule limits the damage of an attack, and it also limits what the agent can do.

8. Put a person before high-impact actions#

A human approval gate pauses the agent before a critical or high-impact action until a person approves it (94:00). Three rules keep a gate real:

9. Track untrusted data#

Information flow control, also called taint tracking, labels data that came from an untrusted source and follows it through the system. Song names two problems: over-tainting, when too much is labeled, and runtime overhead (92:00).

What each layer stops#

Layer Stops Does not stop Cost
Input filter Known and obvious payloads Rephrased, hidden, or adaptive payloads Latency, tokens, blocked legitimate users
Spotlighting Some naive payloads An attacker who types your marker Tokens
Instruction hierarchy Attacks the model was trained on Attacks it was not trained on, or your own fine-tune None, if the provider trained it
Learned detector Payloads similar to its training data New payload families A model call, false positives
Output validation Malformed output, injection into downstream systems A well-formed harmful action Small
Policy gate on actions Any action outside the task's privileges Actions the policy wrongly allows Writing and testing policies
Privilege separation and sandbox Damage from one compromised component Misuse of a component's legitimate permissions Engineering
Human approval High-impact actions nobody approved Low-impact harm, approver fatigue People's time

Figure 1. Defense in depth: where each layer sits between untrusted text and the action it tries to cause.

flowchart LR
    I["Untrusted text"] --> G["Input guard"]
    G --> P["Prompt with the data marked"]
    P --> M["Model"]
    M --> O["Output guard"]
    O --> E["Policy gate in code"]
    E -->|"sensitive action"| H["Human approval"]
    E --> X["Executor with least privilege"]
    H -->|"approved"| X
    X --> T["Tools"]

The layers on the left check text, which an attacker can rephrase. The policy gate and the executor check actions, which the attacker cannot talk past.

Worked example#

A policy gate in plain Python: the Progent idea in miniature. It needs no model. Run it with python policy_gate.py.

# policy_gate.py: check every tool call against a per-task policy, in code.
from dataclasses import dataclass

@dataclass(frozen=True)
class Call:
    name: str
    args: dict

# Rules per task. Your code derives the task from the request.
POLICIES = {
    "summarize_email": {"read_email": lambda args: True},
    "send_email": {"send_email": lambda args: "@" in args.get("to", "")
                                            and not args.get("attachments")},
}
SENSITIVE_TOOLS = {"pay", "delete_email", "shell"}

def enforce(task: str, call: Call) -> tuple:
    """Allow only what the task's policy permits. Unknown tasks allow nothing."""
    if call.name in SENSITIVE_TOOLS:
        return False, f"{call.name} is sensitive: needs a human approval gate"
    rule = POLICIES.get(task, {}).get(call.name)
    if rule is None:
        return False, f"{call.name} is not permitted for task {task!r}"
    if not rule(call.args):
        return False, f"arguments of {call.name} violate the policy"
    return True, "allowed"

if __name__ == "__main__":
    print(enforce("summarize_email", Call("read_email", {})))
    print(enforce("summarize_email", Call("send_email", {"to": "a@b.c"})))
    print(enforce("summarize_email", Call("pay", {"amount": 200})))

The output is allowed, then a refusal for the email, then a refusal for the payment. What to observe:

What the practitioners say#

Song's defense story grew across three terms, and her caution stayed the same.

Her Fall 2024 point about model-level defenses still applies. Hardening the model is the provider's work: data cleaning, safety pre-training, alignment after training, and unlearning (82:00). Use it. Do not depend on it alone.

Pitfalls#

Try it#

Add a policy gate to an agent you control, and measure what it costs.

  1. List the tasks your agent handles. For each, list the tools it needs and the rules on their arguments.
  2. Route every tool call through an enforce function with a default of deny.
  3. Run your injection suite from Jailbreaks and Prompt Injection before and after the gate.
  4. Run twenty benign tasks through the gate and count how many it blocks.

You are done when you have three numbers: the attack success rate before the gate, the rate after it, and the share of benign tasks the gate blocked. Every blocked call must be logged with a reason. Stretch goal: split the agent into a planner without tools and an executor that only runs approved calls, and run the executor in a container.

Key takeaways#

Self-check#

  1. Why is a policy gate on tool calls stronger than an input filter against a rephrased injection?
  2. In Progent, why does the policy for "send an email to Alice" change after the agent reads Alice's address?
  3. An agent reads web pages, holds a mailbox, and can send mail. What does the Rule of Two say about it?
  4. What are the two error rates of a learned detector, and what does each cost you?
  5. Which three properties of a human approval gate keep it from becoming a formality?
Show answers 1. The gate checks the action that results, not the words that caused it. A rephrased injection still has to produce a tool call, and the call is checked against the policy. 2. Least privilege: once the address is known, the task needs only to send to that one address, so the policy narrows to it. 3. It has all three properties, which the rule forbids. Split it into components such that no component has more than two. 4. The false positive rate, which blocks legitimate users, and the false negative rate, which lets attacks through. 5. The approver sees the real arguments, only a few actions need approval, and no answer means no action.

Sources#

Next#

→ Runtime Monitoring and Detection, for the layer that watches everything else while it runs.