Lesson 06 · 40 minutes
Stop a server from fetching what it should not
- Show how a "fetch this URL" feature reaches an internal service
- Fix it with a scheme check, a host allowlist and no redirects
- Explain why this flaw matters for AI agents that browse
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Product asks for a link preview: the user pastes a URL, and your server fetches the page to show its title. A security reviewer asks one question: "Can a user make the server fetch something that the user could not reach alone?" Your task is to build the feature on your own machine, answer that question with a working attack on your own "internal" service, close the door, and then extend the allowed list without opening it again.
Recall
Lesson 5. What does the "?" mark in a parameterised query keep apart?
The code (the SQL) and the data (the value). The driver passes the value separately, so the database never reads it as SQL.
Lesson 4. A user asks for a resource that belongs to someone else. Why does the lesson answer 404 and not 403?
A 403 confirms that the resource exists. A 404 makes "not yours" look the same as "not there". The choice is right when it is made on purpose and used everywhere.
The idea
Your server can reach things that the user cannot: a database port, an admin panel on 127.0.0.1, a cloud metadata address, a file on its own disk. Those services often trust any caller that is already inside, so they ask for no login. Server-side request forgery (SSRF) turns your server into a messenger for the attacker: the attacker gives a URL, and your server fetches it from inside. An AI agent that browses does the same job, because it fetches the URL that a user or a web page gives it. So the flaw applies to agents too.
Three controls close the door:
| Control | What it stops |
|---|---|
| Scheme check | file:// and other schemes that read local files |
| Host allowlist | Any address that you did not choose to allow |
| No redirects | An allowed site that sends the server on to an internal address |
Use an allowlist, a list of what is good. A blocklist of "bad" addresses always forgets one, because an address has many spellings.
- Attacker → Fetch server: fetch http://127.0.0.1:8302/secret
- Fetch server → Internal service: GET /secret, from inside
- Internal service → Fetch server: admin-token=abc123
- Fetch server → Attacker: the secret, in the answer
Worked example
1. Start an "internal" service and a "public" one
Create services.py in ~/krlab/web-apis. Port 8302 plays the internal service, with a secret and no login. Port 8303 is a public site, and its path /go redirects to the internal one. A redirect is a response with a status such as 302 and a Location header: it tells the client to go to another URL. The module threading runs the internal server in the background of the same program. daemon=True stops that thread when the program stops.
services.py
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
class Public(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/go": # a redirect, like many real sites send
self.send_response(302)
self.send_header("Location", "http://127.0.0.1:8302/secret")
self.end_headers()
else:
self.send_response(200); self.end_headers()
self.wfile.write(b"public page")
class Internal(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.end_headers()
self.wfile.write(b"INTERNAL: admin-token=abc123")
threading.Thread(target=HTTPServer(("127.0.0.1", 8302), Internal).serve_forever, daemon=True).start()
HTTPServer(("127.0.0.1", 8303), Public).serve_forever()cd ~/krlab/web-apis
echo "private lab file" > private.txt
python3 services.pyLeave it running. Use a second terminal, and type cd ~/krlab/web-apis in it first.
2. Write the flawed fetcher
Create fetcher.py. The path /fetch?url=... fetches the URL that it receives and returns the body. Four things are new:
urllib.request.urlopenis the standard library function that fetches a URL.urlsplitcuts a URL into its scheme (http,file), its netloc (the host and port) and its path:
parse_qsreads the query string into a dictionary.- The status
502 Bad Gatewaymeans that the server could not get an answer from the next server.
Start it in a third terminal (type cd ~/krlab/web-apis first) with python3 fetcher.py. The test line with $PWD needs this folder too.
fetcher.py
import urllib.request
from urllib.parse import parse_qs, urlsplit
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = parse_qs(urlsplit(self.path).query).get("url", [""])[0]
try:
body = urllib.request.urlopen(url, timeout=3).read()
self.send_response(200)
except Exception as e:
body = f"fetch failed: {e}".encode()
self.send_response(502)
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 8301), Handler).serve_forever()3. Fetch a public page, then the internal service
The option -G with --data-urlencode puts the URL into the query string and encodes it, so that the signs : and / do not break the request. The for loop sends four URLs one after the other.
F=http://127.0.0.1:8301/fetch
for u in http://127.0.0.1:8303/ http://127.0.0.1:8302/secret http://127.0.0.1:8303/go file://$PWD/private.txt; do
curl -s -G --data-urlencode "url=$u" $F; echo
donepublic page
INTERNAL: admin-token=abc123
INTERNAL: admin-token=abc123
private lab fileLine 1 is the real feature. Line 2 reads the internal service through your server. Line 3 starts at the public site, which redirects to the secret. Line 4 reads a local file, because urlopen accepts file://. In a real network the internal service is not reachable from outside, but the fetcher is.
- Attacker → Fetch server: fetch http://127.0.0.1:8303/go
- Fetch server → Public site: GET /go
- Public site → Fetch server: 302, go to the internal service
- Fetch server → Internal service: GET /secret
- Internal service → Fetch server: admin-token=abc123
4. Fix it
Stop the fetcher. A 403 Forbidden means that the server understood the request and refuses it. In fetcher.py, add this above class Handler. The class NoRedirect overrides the step in which the client follows a redirect, and build_opener makes a fetcher that uses it. In *args, **kwargs the stars mean "accept any arguments and ignore them here", and return None makes the redirect an error:
ALLOWED_HOSTS = {"127.0.0.1:8303"} # the only servers this app may call
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None # a redirect becomes an error
opener = urllib.request.build_opener(NoRedirect)Inside do_GET, replace the line try: and the next line with:
parts = urlsplit(url)
if parts.scheme not in ("http", "https") or parts.netloc not in ALLOWED_HOSTS:
self.send_response(403); self.end_headers()
return self.wfile.write(b"url not allowed")
try:
body = opener.open(url, timeout=3).read()The first lines check the scheme and the netloc (parts.netloc) before any connection opens. The path is not checked. The opener replaces urlopen, so redirects no longer happen.
5. Run the four URLs again
Start python3 fetcher.py again and repeat the loop of step 3, with -w ' [%{http_code}]' added to curl.
public page [200]
url not allowed [403]
fetch failed: HTTP Error 302: Found [502]
url not allowed [403]Only the allowed host works. The internal address and the file:// URL are refused before a connection, and the redirect stops. Stop both servers with Ctrl+C.
6. The finished file
This is the whole file as it stands after the steps above. The lab files of the course hold it.
The finished file: fetcher.py
fetcher.py
import urllib.request
from urllib.parse import parse_qs, urlsplit
from http.server import BaseHTTPRequestHandler, HTTPServer
ALLOWED_HOSTS = {"127.0.0.1:8303"} # the only servers this app may call
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None # a redirect becomes an error
opener = urllib.request.build_opener(NoRedirect)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = parse_qs(urlsplit(self.path).query).get("url", [""])[0]
parts = urlsplit(url)
if parts.scheme not in ("http", "https") or parts.netloc not in ALLOWED_HOSTS:
self.send_response(403); self.end_headers()
return self.wfile.write(b"url not allowed")
try:
body = opener.open(url, timeout=3).read()
self.send_response(200)
except Exception as e:
body = f"fetch failed: {e}".encode()
self.send_response(502)
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 8301), Handler).serve_forever()Your turn
The docs team has a second public site and wants previews of it too. Extend your own lab. There are no steps here.
- Write a new file
docs.pythat starts a server on port 8304. Copy the shape of the classPublicfromservices.py. The path/answersdocs page. The path/oldredirects tohttp://127.0.0.1:8304/new. Start it in its own terminal, next toservices.py. - Add
127.0.0.1:8304to the allowed hosts of your fixedfetcher.py, and restart it. - Fetch these four URLs through
/fetchand read the status of each:http://127.0.0.1:8304/,http://127.0.0.1:8304/old,http://127.0.0.1:8305/, andhttp://127.0.0.1:8304@127.0.0.1:8302/secret. In that last URL, the text before the@is a user name, and the real host is127.0.0.1:8302.
Last, explain why the redirect to an allowed host is still refused. Then say what you would change if the docs team needs that redirect to work, and what risk the change brings.
Check yourself
Why does the redirect case need its own control when the host allowlist already exists?
The allowlist checks the URL that the user sent. A redirect makes the client connect to a new URL that the check never saw. Without a redirect control, an allowed host can send your server anywhere.
Why is a blocklist that bans "127.0.0.1" weak?
The same address can be written as localhost, 127.1, 0x7f000001, [::1] or a DNS name that points to it. An allowlist names what you accept and ignores all the spellings.
An AI agent can open any URL that a user pastes. What could go wrong?
The agent fetches from inside your network, so a pasted link can reach internal services or cloud credentials. A page that it reads can also hide instructions for the model. Restrict where the agent may go, and give it no powers that you would not give the page's author.
Field notes
- The lab prints the error text (
fetch failed: ...) so that you can see what happens. In production answer a fixedcannot fetchand write the detail to the log, because the text can show a caller what the server saw inside the network (the help desk in lesson 11 does so). - OWASP lists SSRF in two places. The API Security Top 10 (2023) has "Server Side Request Forgery" as its own item. The OWASP Top 10 had it as item A10 in the 2021 edition; the 2025 edition folds it into "Broken Access Control". Always say which edition you mean.
- Cloud servers answer at a link-local metadata address (169.254.169.254) with the temporary credentials of the machine. This is the classic SSRF target. Use the provider's hardened metadata mode, and block that address at the network edge.
- A host allowlist by name is not final. A name can resolve to a private address, and the answer can change between your check and your fetch (DNS rebinding). For user-chosen hosts, resolve the name yourself, refuse private and link-local ranges, and connect to the address that you checked.
- Network rules are the strongest layer. Run the fetching component in a network that cannot reach internal services, and give it only an outbound route to the internet.
- Limit the size and the time of the fetch, and the types that you accept. A fetch of a huge file or a slow server is an attack on your resources.