Lesson 1 of 20 · 15m
Trust boundaries: every input is hostile until proven otherwise
Map where untrusted data enters — headers, webhooks, stored fields — and apply normalize → allowlist → encode in that order.
A request hits your application carrying about thirty fields you didn't create. The path, the query, every header, every cookie, the body, the filename on a multipart part — all of it was written by whoever sent the request. Host is attacker-writable. X-Forwarded-For is attacker-writable. The Referer you're logging is attacker-writable. None of it is yours.
The wrong mental model is that "input" means form fields. Input is every byte that crosses from outside your process into code that assumes it is well-formed. A bio saved in March is hostile when you render it in November — trust boundaries cross time, not just requests.
The boundary map
- Query strings, form fields and JSON bodies — the obvious ones.
- Headers.
Hostfeeds your URL builder,X-Forwarded-Forfeeds your rate limiter and your logs,Content-Typefeeds your parser.Authorizationhad better be checked, but so had the boring ones. - Cookies — clients edit them freely.
- Uploads: the filename, the declared MIME type and the bytes. Three separate lies.
- Webhooks and partner APIs. "It came from Stripe" is true only after
stripe.webhooks.constructEvent(raw_body, sig_header, secret)returns — and you pass the raw body, because re-serialized JSON will not match the signature. - Anything environmental the attacker can influence: filenames on shared storage, DNS answers, redirect targets. And HTTP parameter pollution —
?id=1&id=2resolves differently in every framework: PHP's$_GETkeeps the last value (id=2), JSP'sgetParameterand Flask'srequest.args.getreturn the first, Express hands you["1","2"], ASP.NET joins them as"1,2". A signature or WAF rule computed over one parser's answer is bypassed by whatever yours sees.
Two subtleties worth naming. The body parser is chosen by Content-Type, which the client controls — an endpoint that parses the body as JSON regardless of what was declared has let the attacker pick the interpreter (and it matters for CSRF, where a text/plain body needs no preflight). And "input" includes data that came back: rows from your own database, cache entries, a partner API's response. Second-order injection is exactly that — written in safely through a parameterized query, concatenated into a later one.
Normalize, validate, encode — in that order
The order is load-bearing. Get it wrong and a check passes on text the interpreter will rewrite:
- Decode every layer before checking.
%2e%2e%2fis../once the framework decodes it, and some stacks decode twice. A validator that runs before the last decode is checking a different string than the one the filesystem sees. - Fold Unicode before comparing. NFKC turns
Kintokand full-width<into<; validate the folded form you will actually store. - Then allowlist.
^[a-z0-9_]{3,24}$says what a username is. Denylists enumerate what isn't, and they always miss a variant.
import re, unicodedata
USERNAME = re.compile(r"[a-z0-9_]{3,24}")
def clean_username(raw: str) -> str:
name = unicodedata.normalize("NFKC", raw).strip().lower() # normalize first
if not USERNAME.fullmatch(name): # then allowlist
raise ValueError("invalid username")
return nameFail closed, and say little
A failed check means reject the request — not fix-up-and-continue, and not a detailed error. invalid username teaches nothing; a different response for "no such user" versus "wrong password" teaches an attacker which accounts exist. For objects the caller should not be able to confirm exist at all, return 404, not 403.
The canonical bug: trusting Host
Password-reset poisoning is the clean demonstration. Your mailer builds https://#{Host}/reset?token=…. An attacker requests a reset for the victim's address with Host: evil.example. The victim receives a real email containing a real token on the attacker's domain; one click hands the token over. The fix is not "sanitize Host" — it is a configured canonical base URL (APP_BASE_URL=https://app.example.com) that request data can never touch.
Its quiet sibling is X-Forwarded-For: if your rate limiter or audit log keys on it raw, one spoofed header resets the attacker's quota — or pins the abuse on someone else. Take the client IP from the hop your reverse proxy actually terminated, not the header the client sent it.
Practice
Draw the boundary map for each route: which untrusted fields reach it, and which interpreters they reach — SQL, a shell, HTML, the filesystem, an outbound URL. At each crossing: normalize, allowlist-validate on the way in, context-encode on the way out, and fail closed.
Keep reading
Related articles from the SudoSecurity blog.
Building a Production REST API With Node.js and Express
Build a REST API in Node.js and Express the way production systems need: input validation, JWT auth, refresh token rotation, status codes, rate limiting, idempotency keys, and centralized error handling.
RSA in JavaScript Part 2: The JWT Is Where You'll Actually Meet It
Most JavaScript developers never call an RSA function directly. They verify an RS256 token, and two classic attacks turn that into an authentication bypass — both demonstrated here, both fixed by one line.
RSA Signatures: The Version in Most Tutorials Is Forgeable
Signing is encryption with the keys swapped, and that symmetry is exactly what makes the naive implementation breakable. Here are two forgeries executed against textbook RSA signatures, and what PSS does that hashing alone cannot.
Ask Java for AES and You Get ECB. Nobody Warns You.
Cipher.getInstance("AES") compiles, runs, encrypts, decrypts, and hands you the weakest mode in the box. Here is the OpenJDK source that makes that decision, and the line where ECB gets chosen for you.