Day 4 of 560 minExploit ArchitectHands-on lab

Day 4: Confused Deputy, SSRF and Approval Spoofing

Taught by Mr Elite Updated

By the end of today you can

  • Explain how a scanning agent's network reach becomes an attacker's reach
  • Demonstrate SSRF through a fetch tool against a local test service, then block it
  • Build an approval gate that renders the real command from code and binds approval to it
  • Spoof a model-written approval summary in the lab and explain why code rendering stops it

Warm-up

Answer from memory first, then tap to check. Recalling yesterday is what makes it stick.

Why should any step that reads banners or fetched pages have its tools removed?

Because the text is written by the target. If the model obeys it and still holds tools, hostile data can trigger actions.

Why do you put -- before positional values in a scanner call?

So a hostile value that starts with a dash is treated as a target, not parsed as an option.

Your agent sits inside your network with a scanner, a fetch tool and a service account. A page it fetches in stage two contains one polite line asking it to retrieve http://127.0.0.1:8081/admin and include the response in the report. The agent obeys. The page never touched your internal service. Your agent did, with your reach.

That is a confused deputy: a trusted component with real privileges, steered into using them for someone who has none. Today you will build that failure on your own machine, close it, and then deal with the human check that is meant to catch it, because a human reading a model-written summary is not a control.

The deputy and its borrowed reach

A deputy is anything acting on your behalf with your authority. A scanning agent has three kinds of authority the attacker lacks: network position (it can reach RFC 1918 ranges and cloud metadata), credentials (API keys, scan tokens), and your approval flow. Yesterday you saw that hostile output can steer the model. Today the question is what that steering can reach.

The attacker does not need to break anything. They only need the agent to make a request that the attacker could not make directly, and to hand back the answer. Output handling from day 3 is the entry point. The fetch tool is the exit.

Here is the habit I want you to build. For any agent you design, write down what its host can reach that the outside world cannot: internal web panels, databases, the metadata service, files on disk. Each item on that list is something a hostile page could ask the agent to fetch. If you cannot shorten the list, you must at least control which requests the model may aim at it.

Confused deputy
A privileged component tricked into using its authority for a party that should not have it.
SSRF
Server-side request forgery. You make a server fetch a URL of your choosing, usually something internal.
TOCTOU
Time of check versus time of use. The thing you checked changes before you act on it.
Loopback
The address 127.0.0.1, which always points back at the same machine. Only local programs can reach services bound to it.

Quick check

A page fetched by your agent tells it to request an internal admin URL. Which part is the confused deputy?

SSRF through a fetch tool

Most pipelines give the agent a fetch or http_get tool so it can read a login page or a robots.txt. If the tool accepts any URL, the model decides where your network traffic goes, and the model is reading hostile text. Four things go wrong: loopback and private addresses, cloud metadata at 169.254.169.254, redirects that bounce a safe-looking URL to an internal one, and DNS names that resolve to internal addresses.

A string check on the hostname fails against that last case. You must resolve the name, inspect the resulting IP addresses, and refuse private, loopback, link-local and reserved ranges. Then you must stop redirects, or re-check each hop.

Notice how many ways one address can be written. 127.0.0.1, localhost, 127.1 and the single number 2130706433 all point at your own machine. A blocklist of strings will always miss one. A check on the resolved address does not care how the attacker spelled it, which is why we use it.

Watch me do it: SSRF in, SSRF out

Everything here runs on your own machine against 127.0.0.1. Nothing leaves your computer and no third-party system is involved. You need Python 3 and curl. Run python3 --version to confirm Python prints a version number. If the command is not found, install Python 3 from python.org first.

python
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers()
        self.wfile.write(b"INTERNAL ADMIN: scan-token=demo-not-real\n")
HTTPServer(("127.0.0.1", 8081), H).serve_forever()
internal.py: a fake internal-only service on loopback. The token is a harmless demo string.
python
import ipaddress, socket, urllib.request
from urllib.parse import urlparse

def fetch_naive(url):
    return urllib.request.urlopen(url, timeout=5).read(300).decode(errors="replace")

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k):
        return None

def fetch_safe(url):
    p = urlparse(url)
    if p.scheme not in ("http", "https") or not p.hostname:
        raise ValueError("bad url")
    for ai in socket.getaddrinfo(p.hostname, p.port or 80):
        ip = ipaddress.ip_address(ai[4][0])
        if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
            raise ValueError(f"blocked {ip}")
    opener = urllib.request.build_opener(NoRedirect)
    return opener.open(url, timeout=5).read(300).decode(errors="replace")
fetch_tools.py: the safe version allows only http and https, resolves the name, rejects internal ranges and refuses redirects.
bash
python3 -c "from fetch_tools import *; print(fetch_naive('http://127.0.0.1:8081/'))"
python3 -c "from fetch_tools import *; print(fetch_safe('http://127.0.0.1:8081/'))"
The first call leaks the token. The second raises ValueError: blocked 127.0.0.1.
bash
python3 -c "from fetch_tools import *; print(fetch_naive('http://2130706433:8081/'))"
python3 -c "from fetch_tools import *; print(fetch_safe('http://2130706433:8081/'))"
The same loopback address written as one integer. A string blocklist would miss it, the resolved-IP check does not.

What just happened: the naive tool did exactly what the URL said, so whoever controls the URL controls your traffic. The safe tool asked the operating system where the name points, then judged the answer. That is the whole idea, and it is small enough to fit in twenty lines.

Approval: who writes what the human reads

The usual answer to a risky agent is a human approval step. It only works if the human sees the truth. If the model writes the approval text, then the model, which is reading hostile input, decides what the human believes. An attacker who can shape the summary can get a harmful action approved with a smile on the screen.

The rule is simple. The action is rendered from the structured tool call by code. The model's summary may appear, but it is labelled unverified and sits below the real action. The reviewer sees the exact binary, the full argument list and the resolved target.

Then there is TOCTOU. If approval attaches to a description, the arguments can change between click and execution. Bind approval to a hash of the exact argument list, and recompute that hash immediately before running.

One more habit makes the screen harder to fool: make the reviewer do a small active step. In the gate below you type a short ID instead of pressing Enter. It is a tiny speed bump, but it stops the reflex of approving without reading.

Quick check

Where should the text a human approves come from?

Watch me do it: an approval gate that cannot be talked round

Stay in your day4 folder. This gate never needs nmap to be installed for the first two tests, because the first only displays the command and the second stops before anything runs. The third test uses echo, which every system has.

python
import hashlib, json, shlex, subprocess

def digest(argv):
    return hashlib.sha256(json.dumps(list(argv)).encode()).hexdigest()[:12]

def approve(argv, model_summary):
    print("MODEL SAYS (unverified):", model_summary[:200])
    print("ACTUAL COMMAND:", shlex.join(argv))
    print("ID:", digest(argv))
    if input("Type the ID to approve: ").strip() != digest(argv):
        return None
    return (tuple(argv), digest(argv))

def run(approved):
    argv, d = approved
    assert digest(argv) == d, "arguments changed after approval"
    return subprocess.run(list(argv), capture_output=True, text=True, timeout=120)
gate.py: the command and ID come from code. Approval is bound to a hash and rechecked before running.
bash
python3 -c "from gate import *; approve(['nmap','-sT','-p-','--','127.0.0.1'], 'Quick check of port 80 only')"
python3 -c "from gate import *; run((('nmap','-p-','127.0.0.1'), 'abc123abc123'))"
First: the ACTUAL COMMAND line exposes the lie. Second: the stale hash triggers the AssertionError.
bash
python3 -c "from gate import *; a=approve(['echo','hello'],'Print a greeting'); print(run(a).stdout if a else 'refused')"
A matching approval runs. Type the ID shown and you get hello. Type anything else and you get refused.

What just happened: the lie lived only in the model's sentence, and the code line next to it contradicted it. The reviewer does not need to be clever, only to read the line that code produced. The hash then stops a swap after the decision.

Lab: spoof the summary

You have built the defence. Now meet the weakness it fixes. The lab ai-approval-summary-spoof-1 gives you LedgerBot, where a human approves from a friendly summary. Work through it as the attacker. A companion lab, ai-confused-deputy-1, covers the privilege side with FinanceBot if you finish early. Both run in the SecurityElites browser environment, so nothing here touches a real system.

Start by only observing. Use the bot normally once and read what the reviewer sees. Then ask which words you control and where they end up. Keep a note of each attempt and what the summary said, because comparing summary against raw call is the skill you are practising.

Your turn

AI Human-in-the-Loop Bypass

LedgerBot pays vendors only after Ravi approves, but Ravi reads a summary the model writes while the raw tool call hides behind a toggle. This is the exact design flaw we just removed from gate.py, so use the lab to feel why it fails.

Open the lab in a new tab

What to try

What to notice

  • Which fields in the call are rendered by code and which are written by the model.
  • How little a reviewer checks when the summary sounds routine.
  • What single design change would make your attempt visible at a glance.

If it did not work

Validating the URL string instead of the resolved IP

Resolve the hostname, check every returned address against private, loopback, link-local and reserved ranges, and refuse redirects or re-check each hop.

Showing the model's summary as the main approval text

Render the command from the argument list in code. Show any model text below it, labelled unverified.

Approving a description and running a later, mutable version

Hash the exact argument list at approval and recompute it right before execution.

Relying on approval alone to stop SSRF

Combine it with network isolation. Run the fetch tool where internal ranges and metadata are unroutable.

Recap

  • A confused deputy uses the agent's own reach and credentials for someone else.
  • Any fetch tool the model can aim is an SSRF primitive until you constrain it.
  • Check resolved IPs, not hostnames, and handle redirects.
  • Humans must read an action rendered by code. A model-written summary is attacker-influenced text.
  • Bind approval to a hash of the exact arguments and recheck before execution.
  • Network isolation backs up code checks that can have gaps such as DNS rebinding.

Cheat sheet

ipaddress.ip_address(ip).is_private
Python check for internal ranges. Pair with is_loopback, is_link_local, is_reserved.
socket.getaddrinfo(host, port)
Resolves every address a name maps to, so you can vet them all.
shlex.join(argv)
Renders an argument list as the exact command line for display.
sha256(json.dumps(argv))
Fingerprint that ties approval to one exact action.
169.254.169.254
Cloud metadata address. Always block it from agent fetch tools.
TOCTOU
Gap between check and use. Close it by rechecking at execution.

Before the next day

Mission: Gate it, then try to lie to it

Add an approval step to the scanner wrapper you built on day 2 that prints the exact command and target generated by code, then spend time trying to make a model summary disagree with it. The point is to learn what the reviewer actually sees when the model is hostile or confused.

About 35 min

You are done when: gate.py wired into your wrapper, plus notes_day4.md with three summary-versus-command comparisons and your short conclusion.

Want more? Add a fetch_safe that connects to the vetted IP directly and runs in a Docker container with no route to internal networks, then prove the rebinding gap is closed.

Quiz

4 questions. Your score is saved with your progress.

1. Why does blocking the hostname "localhost" fail as an SSRF defence?

2. An approval screen shows a model-written summary and hides the raw call. What is the core flaw?

3. What does binding approval to a hash of the argument list protect against?

4. Which control best limits damage if your IP check has a rebinding bug?

Finish the day

Mark the day complete to save your progress.

Next: Day 5 is the capstone. You assemble the full pipeline, attack it with everything from days 3 and 4, fix what breaks and document the evidence. Coming soon.

Tell someone you are doing this:WhatsAppXLinkedIn

Your notes

Private to this device. Write what you want to remember from today.