Topic 3 of 6 · 4 min read
Trusting input: SSRF, uploads and deserialization
Goal: Find where AI-written code trusts user-controlled input and add the validation or allow-list that closes the hole.
Whenever generated code fetches a URL, saves a file or parses a payload that a user supplied, it has to decide how far to trust it. Models usually trust it completely.
Check yourself · 1 of 3
An AI-written feature fetches any URL the user types and returns the page text. Which attack does this allow?
Why it matters
Features like "import from a link", "upload an avatar" and "restore a backup" are common tasks. The shortest working code fetches the URL, writes the file with the name it came with, or loads the data with a general-purpose parser. Each shortcut is a known weakness: server-side request forgery (SSRF), unrestricted upload and insecure deserialization.
How each one works
- SSRF. The server fetches a user-given URL. The attacker gives an internal address such as
http://169.254.169.254/(a cloud metadata service) orhttp://localhost:6379. The server reaches places the attacker cannot. - Unsafe uploads. The code trusts the file name, the extension and the
Content-Typeheader. An attacker uploads a script, an oversized file, or a name with../, and may get it served or executed. - Unsafe deserialization. Formats such as Python
pickle, and YAML loaded with an unsafe loader, can run code while being parsed. JSON is data only.
How to close each hole
- URLs: parse them, allow only
https, match the host against an allow-list, resolve the address and refuse private ranges, and do not follow redirects blindly. - Uploads: generate your own file name, check size, check the actual content type by reading bytes, store outside the web root, and never execute it.
- Parsing: use JSON, or a safe loader such as
yaml.safe_load. Never unpickle data from a user.
Before and after
# Before: fetches anything the user names
def import_from_url(url):
return requests.get(url, timeout=10).text
# After: allow-listed host, https only, no redirects
ALLOWED = {"cdn.example.com", "files.partner.io"}
def import_from_url(url):
u = urlparse(url)
if u.scheme != "https" or u.hostname not in ALLOWED:
raise ValueError("URL not allowed")
return requests.get(url, timeout=10, allow_redirects=False).text
What goes wrong
- Checking the string, not the address. A blacklist for "localhost" misses
127.1, a DNS name pointing at a private IP, or a redirect. - Trusting the extension.
avatar.pngcan contain anything. - Validating the front end only. Direct requests skip it.
- Reaching for pickle or an unsafe YAML load because the agent copied the first example it knew.
Examples
The link preview that reads cloud credentials
app.post("/preview", async (req, res) => {
const html = await fetch(req.body.url).then(r => r.text());
res.json({ title: extractTitle(html) });
});
A request with url=http://169.254.169.254/latest/meta-data/ makes the server read its own cloud metadata. Add a host allow-list or, for a general preview, resolve the IP and reject private and link-local ranges.
The upload that keeps the user file name
const dest = path.join("public/uploads", file.originalname);
fs.writeFileSync(dest, file.buffer);
A name such as ../../app.js overwrites code, and a .html file is served from your domain. Generate a random name, enforce a size limit and an allowed type list, and store outside the public folder.
Key points
- Any URL, file or payload from a user must be validated before the server fetches, stores or parses it.
- SSRF defenses use https-only, a host allow-list, private-address checks and no blind redirect following.
- For uploads, ignore the client file name, limit size, check real content and store outside the web root.
- Parse untrusted data with JSON or safe loaders; pickle and unsafe YAML loading can execute code.
- Validation must run on the server, because the client can be bypassed.
Common mistakes
- Blocking the word "localhost" and assuming internal addresses are covered.
- Trusting the file extension or Content-Type header sent by the client.
- Using the user-supplied file name when writing to disk.
- Loading user-supplied YAML or pickled data with a loader that can build arbitrary objects.
Check yourself · 2 of 3
A user uploads a file named avatar.png. Which handling is safest?
Check yourself · 3 of 3
You need to load a config file that users can edit in Python. Which choice avoids code execution during parsing?
Practice items, not counted towards your mastery.
Start here
- CWE Top 25 Most Dangerous Software Weaknesses (MITRE) (opens in a new tab)DocsFree
The ranked list of weakness classes, including injection and broken access control, that generated code should be checked against.
- Do Users Write More Insecure Code with AI Assistants? (opens in a new tab)PaperFree
A user study showing assistant users wrote less secure code while feeling more sure of it.
- OWASP Top Ten (opens in a new tab)StandardFree
The standard awareness list of web application risks, from access control to misconfiguration.
More for this topic
- Server-Side Request Forgery Prevention Cheat Sheet (OWASP) (opens in a new tab)ArticleFree
Allow-list, DNS and redirect handling for code that fetches user-supplied URLs.
- File Upload Cheat Sheet (OWASP) (opens in a new tab)ArticleFree
Concrete controls for names, types, sizes and storage of uploaded files.