Application & Web Security
Application & Web Security Cheatsheet
Actionable Attack & Defend rules across OWASP Top 10, PostgreSQL injection, XSS/CSP, JWT/CORS, Web Crypto, ReDoS/SSRF, and Linux hardening. Print to PDF with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
1. Core Security Invariants & Code Review Checklist
Run every trust boundary change through these five non-negotiable rules.
- Normalize & decode ONCE before validation; reject double-encoding (%252e) and null bytes.
- Enforce positive allowlists (exact regex, schema, or host list) — never substring blocklists.
- Pair authentication with object & tenant authorization checks (actor.tenantId === row.tenantId).
- Pin cryptographic algorithms server-side (ignore JWT header.alg === "none") and verify signatures BEFORE parsing untrusted claims.
- Fail closed everywhere: catch blocks and missing policies must return null / 403 / #, never allow.
2. SQL Injection & PostgreSQL Defense Matrix
| Context | Vulnerable Pattern | Safe Fix |
|---|---|---|
| Data values (WHERE / INSERT / UPDATE) | EXECUTE 'SELECT * FROM u WHERE email = ''' || v_email || '''' | EXECUTE 'SELECT * FROM u WHERE email = $1' USING v_email |
| Column names & ORDER BY directions | EXECUTE 'SELECT * FROM p ORDER BY ' || sort_col | CASE WHEN p_sort = 'price_desc' THEN price END DESC (strict allowlist) |
| Multi-tenant object access (IDOR) | WHERE id = $1 | WHERE id = $1 AND tenant_id = $2 (session tenant from verified token) |
| Sensitive projections (UNION resistance) | SELECT * FROM products WHERE ... | Explicit safe column list (never api_keys / password_hash) |
3. XSS Contexts, CSP, Cookies & CORS Headers
| Vector / Header | Weak / Broken | Hardened Standard |
|---|---|---|
| HTML body & attributes | innerHTML = raw; partial <script> replace | textContent or 5-char escape (& first, <, >, ", ') |
| <a href={url}> URI context | escapeHtml(url) alone | new URL(cleaned, base).protocol in {"https:", "http:"} else "#" |
| Content-Security-Policy | script-src 'self' 'unsafe-inline' 'unsafe-eval' * | default-src 'none'; script-src 'nonce-<rng>' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none' |
| Session Cookie | Set-Cookie: sid=abc; Path=/ | Set-Cookie: sid=abc; HttpOnly; Secure; SameSite=Strict; Path=/ |
| CORS Policy with Credentials | Reflect req.headers.origin OR allow "*" / "null" | Normalized new URL(origin).origin inside exact server allowlist |
4. Web Crypto Recipes (HMAC, PBKDF2, AES-GCM, Constant-Time)
Copy-ready primitives running natively via crypto.subtle in modern browsers and Node.
HMAC-SHA256 Sign & Verify (constant-time verify)
const key = await crypto.subtle.importKey( 'raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify'], ); const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(JSON.stringify(fields))); const ok = await crypto.subtle.verify('HMAC', key, macBytes, dataBytes);crypto.subtle.verify performs constant-time HMAC tag validation.
AES-GCM Authenticated Encryption (fresh 96-bit IV + AAD)
const iv = crypto.getRandomValues(new Uint8Array(12)); const ciphertext = await crypto.subtle.encrypt( { name: 'AES-GCM', iv, additionalData: new TextEncoder().encode('tenant:' + tenantId) }, aesKey, new TextEncoder().encode(plaintext), );Never reuse an IV with the same AES key; reuse allows XOR plaintext recovery.
PBKDF2 Password Derivation (>= 100,000 iterations, 16-byte random salt)
const baseKey = await crypto.subtle.importKey( 'raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveBits'], ); const bits = await crypto.subtle.deriveBits( { name: 'PBKDF2', salt: saltBytes, iterations: 210_000, hash: 'SHA-256' }, baseKey, 256, );
5. ReDoS, Secret Scanning & SSRF URL Parsing
| Domain | Trap to Avoid | Safe Verification Pattern |
|---|---|---|
| Slug Regex (ReDoS) | ^([a-z0-9-]+)+$ (nested backtracking) | ^[a-z0-9]+(?:-[a-z0-9]+)*$ (delimiter disambiguated) |
| Secret Scanner (CI) | /password/gi noisy grep | \bAKIA[0-9A-Z]{16}\b | \bghp_[A-Za-z0-9]{16,}\b | -----BEGIN [A-Z ]*PRIVATE KEY----- |
| Path Traversal | path.startsWith('/srv/uploads') or .replace('../', '') | Canonical normalize after decode + resolved.startsWith('/srv/uploads/') + fs.realpathSync |
| SSRF Webhook Fetch | url.startsWith('https://trusted.example') | new URL(): require https:, block username/password, block RFC1918/169.254/loopback, pin resolved IP |
6. Linux Incident Forensics & Hardening Commands
Extract attacker traces & brute-force SSH attempts without mutating logs
grep '203.0.113.42' /var/log/nginx/access.log > /home/user/web-incident.log grep 'Failed password' /var/log/auth.log > /home/user/ssh-bruteforce.logLock exposed secrets & SSH keys, kill persistence, delete dropped shells
ps aux kill -9 2048 chmod 600 /home/user/.ssh/id_rsa chmod 600 /home/user/webapp/.env chown user:user /home/user/webapp/config.json && chmod 640 /home/user/webapp/config.json rm /var/www/app/uploads/shell.shAlways rotate any secrets that were readable before containment.
7. OAuth 2.1, Concurrency, Supply Chain & LLM Guardrails
| Threat Domain | Vulnerable Pattern | Defensive Standard |
|---|---|---|
| OAuth 2.1 / OIDC Login | No state CSRF check, prefix redirect_uri, signature-only JWT check | PKCE S256 (SHA-256) + constant-time state + exact origin+pathname + iss/aud/azp/nonce verify |
| TOCTOU & Idempotency | SELECT balance -> UPDATE balance; non-idempotent POST retries | Atomic UPDATE ... WHERE balance >= $amount RETURNING; DB UNIQUE ON CONFLICT DO NOTHING |
| Rate Limiting & Proxies | Trusting client X-Forwarded-For.split(',')[0] | Rightmost trusted proxy hop boundary + sliding-window request timestamps |
| CI/CD & Supply Chain | Inline run: "${{ github.event.pull_request.title }}" & postinstall hooks | Bind untrusted inputs via env: "$VAR", npm ci --ignore-scripts, pin SRI sha256-... digests |
| LLM / RAG / Agent Tools | Raw web text inside prompt, unscoped RAG vector SQL, free-form Markdown/tool dispatch | Escape XML delimiters, SQL tenant_id = $1 AND (...), typed tool allowlist + HTTPS URL validation |
8. Copy-Paste Recipes: OAuth PKCE, Atomic SQL, CI/CD & LLM Guardrails
Derive PKCE S256 challenge & pin exact OAuth redirect_uri
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier)); const challenge = btoa(String.fromCharCode(...new Uint8Array(digest))) .replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); const u = new URL(rawRedirectUri); const isAllowed = u.protocol === 'https:' && !u.username && !u.password && !u.hash && allowlist.includes(u.origin + u.pathname);Always enforce code_challenge_method=S256 and exact HTTPS origin+pathname equality.
Single-statement atomic SQL debit + ON CONFLICT idempotency
INSERT INTO sec_transfer_requests (idempotency_key, account_id, amount_cents) VALUES ($1, $2, $3) ON CONFLICT (idempotency_key) DO NOTHING; UPDATE sec_wallets SET balance_cents = balance_cents - $3 WHERE account_id = $2 AND balance_cents >= $3 RETURNING balance_cents;GitHub Actions safe env binding & npm ci --ignore-scripts lockdown
# Never inline ${{ github.event.pull_request.title }} inside run: env: PR_TITLE: ${{ github.event.pull_request.title }} run: echo "PR: $PR_TITLE" # Install pinned lockfile cleanly without executing untrusted postinstall scripts npm ci --ignore-scriptsEscape untrusted LLM delimiters & scope RAG tenant SQL with ESCAPE
-- Always parenthesize OR clauses after tenant_id = $1! SELECT id, tenant_id, title, chunk_text FROM sec_rag_documents WHERE tenant_id = $1 AND (title ILIKE '%' || $2 || '%' ESCAPE '!' OR chunk_text ILIKE '%' || $2 || '%' ESCAPE '!') ORDER BY id ASC LIMIT 5;Also escape &, <, > globally in untrusted RAG chunks wrapped inside <untrusted_data>.