Topic 4 of 5 · 5 min read
Validating input and encoding output
Goal: Spot injection, path traversal or SSRF in generated handler code and choose the defence that fits each.
Treat every value that crosses your boundary as hostile text: validate its shape on the way in, keep it as data when you use it, and encode it on the way out. Most injection flaws come from one move: building a command or a query by gluing strings together.
Check yourself · 1 of 3
What is the best defence against SQL injection?
Why it matters
A model has seen thousands of examples that concatenate strings into SQL or paths, because tutorials do. It reproduces the pattern when it is the shortest way to a working answer. The code passes tests with friendly input and fails when the input is not friendly.
The four defences
- Validate at the boundary. Use a schema library (Zod, Pydantic, JSON Schema) to check type, length, range and allowed values. Reject early. Prefer allowlists to blocklists.
- Parameterise. Pass values separately from the query:
db.query("SELECT * FROM users WHERE email = $1", [email]). The same idea applies to shell commands: pass an argument array, not one string. - Encode output for its context. HTML, URL, SQL and shell each need different escaping. Use the framework's templating, which escapes by default, and avoid
innerHTMLanddangerouslySetInnerHTMLwith user text. - Constrain where the input points. For file paths, resolve the full path and check it stays inside the intended folder. For URLs the server fetches, check the host against an allowlist.
Three patterns to know
- Injection:
"SELECT ... WHERE id = " + idlets1 OR 1=1change the query. - Path traversal:
fs.readFile("./uploads/" + name)lets../../etc/passwdescape the folder. - Server-side request forgery (SSRF):
fetch(req.body.url)lets a caller make your server call internal addresses such as a cloud metadata service.
Before and after
// Before
const file = await fs.readFile(path.join(UPLOADS, req.query.name));
// After
const full = path.resolve(UPLOADS, req.query.name);
if (!full.startsWith(path.resolve(UPLOADS) + path.sep)) return res.status(400).end();
const file = await fs.readFile(full);
What goes wrong
- Escaping by hand instead of using parameters, then missing one case.
- Validating only on the client. The caller can skip the browser.
- Blocklisting. Filtering
..orlocalhostmisses encoded and alternative forms; allowlist instead.
Examples
An SSRF in a preview feature
@app.post('/preview')
def preview():
return requests.get(request.json['url']).text
A caller sends http://169.254.169.254/ and the server returns data from the cloud metadata service. Fix: parse the URL, allow only https and a short list of approved hosts, and set a timeout and size limit.
Key points
- Validate type, length and allowed values at the boundary and reject bad input early.
- Use parameterised queries and argument arrays, never string concatenation, for SQL and shell commands.
- Encode output for its context and prefer templating that escapes by default.
- For file paths, resolve the full path and confirm it stays inside the intended directory.
- For server-side fetches of user-supplied URLs, allow only known hosts instead of trying to block bad ones.
Common mistakes
- Building SQL or shell commands from strings because the output looks clear and works in tests.
- Relying on client-side validation alone.
- Using a blocklist of bad characters or hosts instead of an allowlist.
- Using
innerHTMLwith text that came from a user.
Check yourself · 2 of 3
A handler runs fs.readFile('./uploads/' + name) where name comes from the URL. What risk does this carry?
Check yourself · 3 of 3
A feature fetches any URL the user types. Which defence fits best?
Practice items, not counted towards your mastery.
Start here
- OWASP Top 10:2025 (opens in a new tab)StandardFree
The ten risk categories, from A01 Broken Access Control to A10 Mishandling of Exceptional Conditions, with examples and prevention advice.
- OWASP Cheat Sheet Series (opens in a new tab)DocsFree
Short, practical prevention guides for each topic in this skill.
- OWASP Application Security Verification Standard (opens in a new tab)StandardFree
A numbered list of security requirements you can cite in review comments.
More for this topic
- Server-Side Request Forgery Prevention Cheat Sheet (OWASP) (opens in a new tab)ArticleFree
Allowlists and network controls for code that fetches user-supplied URLs.
- CWE Top 25 Most Dangerous Software Weaknesses (MITRE) (opens in a new tab)DocsFree
A ranked list of weakness types, useful for naming a finding precisely.