| |

Web Security 21 🛡️ Cheatsheet

⏱️ Estimated read: 10 min | |

A condensed reference across the series — principles, headers, auth, injection classes, rate limiting, secrets, supply chain, LLM security, testing, and incident response. One section per surface, tables over prose, snippets over explanation.


Core Principles

PrincipleMeaningFailure
Least privilegeMinimum scope for the task and the lifetimeShared service account
Defence in depthIndependent layers, no single pointOne WAF, nothing else
Fail secureDeny on errorLimiter fails open on login
Complete mediationCheck every request, every objectAuthz on list, not detail
Separation of dutiesNo single actor holds all powersDev has prod DB write
Assume breachDesign for post-compromiseFlat internal network
Economy of mechanismSimple controls get usedCustom crypto

OWASP Top 10 (2021) / API Top 10 (2023) / LLM (2025)

Web (2021)API (2023)LLM (2025)
A01 Broken Access ControlAPI1 BOLALLM01 Prompt Injection
A02 Cryptographic FailuresAPI2 Broken AuthLLM02 Sensitive Info Disclosure
A03 InjectionAPI3 Property AuthzLLM03 Supply Chain
A04 Insecure DesignAPI4 Resource ConsumptionLLM04 Data Poisoning
A05 Security MisconfigurationAPI5 BFLALLM05 Improper Output Handling
A06 Vulnerable ComponentsAPI6 Business Flow AbuseLLM06 Excessive Agency
A07 Auth FailuresAPI7 SSRFLLM07 System Prompt Leakage
A08 Integrity FailuresAPI8 MisconfigurationLLM08 Vector/Embedding Weaknesses
A09 Logging FailuresAPI9 Inventory ManagementLLM09 Misinformation
A10 SSRFAPI10 Unsafe ConsumptionLLM10 Unbounded Consumption

Ordering note: A01 Broken Access Control is the most reported class; API1 BOLA is its API form and no rate limit mitigates it.


Security Headers

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123';
  object-src 'none'; base-uri 'self'; frame-ancestors 'none';
  img-src 'self' https://cdn.example.com; connect-src 'self';
  form-action 'self'; upgrade-insecure-requests
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
HeaderProtects AgainstNotes
CSPXSS, exfiltrationunsafe-inline defeats it; use nonces
HSTSDowngrade, cookie theftPreload requires 1-year max-age
nosniffMIME confusionRequired with uploads
frame-ancestorsClickjackingReplaces X-Frame-Options
COOP/CORPCross-window leaksRequired for SharedArrayBuffer

Cookies & Sessions

Set-Cookie: sid=<256-bit-entropy>; Secure; HttpOnly; SameSite=Lax;
  Path=/; Max-Age=3600; __Host-sid
AttributeEffectOmit ⇒
SecureHTTPS onlySent over HTTP
HttpOnlyNo JS accessTheft via XSS
SameSite=LaxTop-level GET onlyCSRF on POST
SameSite=StrictNo cross-site at allBreaks external links
Path=/ScopeWrong scope = missing
__Host- prefixRequires Secure, Path=/, no Domain—
Session RuleValue
Token entropy≥ 128 bits, CSPRNG
Rotate onLogin, privilege change, MFA
Idle timeout15–30 min (sensitive), 8 h (general)
Absolute timeout24 h max
StoreServer-side, or encrypted+MAC

Injection Classes

SQL Injection

// ❌ Interpolated
db.query(`SELECT * FROM u WHERE email = '${email}'`);

// ✅ Parameterised
db.query("SELECT * FROM u WHERE email = $1", [email]);

// ✅ Identifier allowlist (names cannot be parameters)
const col = ["name", "created_at"].includes(sort) ? sort : "name";
db.query(`SELECT * FROM u ORDER BY ${col}`);

XSS

TypeVectorFix
ReflectedQuery param echoedContextual encoding
StoredDB content renderedEncode on output
DOMinnerHTML, document.writetextContent, sanitise
Template{{ x }} unescapedFramework auto-escape on
Mutationonerror=, javascript:Allowlist schemes
el.textContent = input;                                   // ✅ text
el.innerHTML = DOMPurify.sanitize(input, {                // ✅ html
  ALLOWED_TAGS: ["p","strong","em","ul","li"],
  ALLOWED_ATTR: [],
});

CSRF

DefenceCoverage
SameSite=LaxBlocks most POST CSRF
Synchronizer tokenPer-session, server-compared
Double-submit cookieStateless, needs signed cookie
Origin / Sec-Fetch-SiteRejects foreign origins
Custom header requirementBrowsers cannot forge preflight
// ✅ Check origin on state-changing requests
if (!TRUSTED_ORIGINS.has(req.headers.origin)) return res.sendStatus(403);
if (req.headers["sec-fetch-site"] === "cross-site") return res.sendStatus(403);

SSRF

// ❌ Model- or user-supplied URL fetched blindly
await fetch(req.query.url);

// ✅ Scheme + host allowlist, resolve then check IP
const u = new URL(raw);
if (!["https:"].includes(u.protocol)) throw new Error("scheme");
if (!ALLOWED_HOSTS.has(u.hostname)) throw new Error("host");
const { address } = await dns.lookup(u.hostname);
if (isPrivateIp(address)) throw new Error("private");       // block 10/8, 172.16/12, 192.168/16, 127/8, 169.254/16, ::1

Deny list to block: 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16 (metadata!), ::1, fc00::/7, 0.0.0.0/8.

Command / Template Injection

// ❌ Shell string
exec(`convert ${file} out.png`);

// ✅ argv array, no shell
execFile("convert", [file, "out.png"]);

// ❌ Template rendered from user input
template.render(userInput);

// ✅ Fixed template, escaping engine, no logic in templates
nunjucks.render("greeting.njk", { name, autoescape: true });
ClassSignalFix
SQLiString concat into queryParameterise
XSSOutput into HTMLEncode / sanitise
CSRFState change without tokenToken + SameSite
SSRFServer fetches user URLAllowlist + IP check
CMDiShell string interpolationexecFile argv
SSTIUser input as templateFixed templates
XXEParser with entity resolutionDisable DTDs
LDAPFilter concatenationEscape RFC 4515
NoSQL{$ne: null} in bodyType-check, allowlist

Authentication

ControlStandard
Password hashingArgon2id: 19 MiB, t=2, p=1 (OWASP)
Alternativebcrypt cost ≥ 12, scrypt N=2^17
Session secret≥ 256 bits, rotated
MFATOTP (RFC 6238) or WebAuthn
PasskeysWebAuthn, origin-bound, phishing-proof
Breach checkPwned Passwords range API (k-anonymity)
ComparisonConstant-time (crypto.timingSafeEqual)
EnumerationIdentical body + timing for unknown user
// ✅ Timing-safe login
const DUMMY = await argon2.hash("timing-placeholder");
const valid = await argon2.verify(account?.hash ?? DUMMY, password);
if (!account || !valid) return { ok: false, error: "invalid_credentials" };

JWT Checklist

CheckRule
AlgorithmPin: algorithms: ["RS256"] — never none
SignatureVerify before reading claims
exp / nbfEnforce with small leeway
aud / issValidate against expected
StorageHttpOnly cookie > localStorage
RevocationNeeds server-side denylist or short TTL
Secrets≥ 256 bits; rotate on compromise

Authorization

// ✅ Object check in the query, not after the fetch
const inv = await db.invoice.findFirst({
  where: { id: req.params.id, customerId: req.user.sub },
});
if (!inv) return res.status(404).json({ error: "not_found" });  // 404 not 403
ModelUseRisk
RBACRoles → permissionsRole explosion
ABACAttribute predicatesPolicy complexity
ReBACRelationship graphTraversal cost
Tenant scopingRow-level tenant_idMissing predicate
FailureCodeMitigation
BOLAAPI1Scope query by subject
BFLAAPI5Default-deny route scopes
Property-levelAPI3Response field allowlist
Mass assignmentA01DTO with explicit fields

TLS & Cryptography

ItemValue
Minimum protocolTLS 1.2, prefer 1.3
Cipher suitesAEAD only (AES-GCM, ChaCha20-Poly1305)
Certificate≥ 2048-bit RSA or P-256 ECDSA
HSTS max-age≥ 31,536,000 s
OCSPStapling recommended
Randomnesscrypto.randomBytes, never Math.random
ALGORITHM CHOICE

  symmetric      AES-256-GCM  or  ChaCha20-Poly1305
  hashing        SHA-256 / SHA-3
  passwords      Argon2id  >  scrypt  >  bcrypt  >  PBKDF2
  key exchange   X25519  >  ECDHE P-256
  signatures     Ed25519  >  ECDSA P-256  >  RSA-PSS
  avoid          MD5, SHA-1, DES, RC4, ECB, RSA PKCS#1 v1.5

API Rate Limiting

AlgorithmBurstBoundary Flaw
Fixed windowAt resetDouble rate at boundary
Sliding windowBoundedNone material
Sliding logNoneMemory ∝ requests
Token bucketUp to capacityNone
Leaky bucketSmoothedDelays legit bursts
-- Atomic token bucket: read, refill, decide, write in one round trip
local s = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens = tonumber(s[1]) or cap
local ts = tonumber(s[2]) or now
tokens = math.min(cap, tokens + math.max(0, now - ts) * refill)
local ok = tokens >= cost
if ok then tokens = tokens - cost end
redis.call("HMSET", KEYS[1], "tokens", tokens, "ts", now)
redis.call("PEXPIRE", KEYS[1], math.ceil(cap / refill))
return { ok and 1 or 0, math.floor(tokens) }
KeySurvives Proxy Rotation
ipNo — collides on NAT
userYes
api_keyYes — hash at rest
sessionPartially
routen/a (coarse)
HeaderMeaning
429 Too Many RequestsRFC 6585
Retry-AfterSeconds to wait
RateLimit-Limit / -Remaining / -ResetIETF draft
X-RateLimit-*Legacy de facto

GraphQL Hardening

ControlLimitBypass
Depth7–10Aliases, fragments
ComplexityArg-scaled budgetNaive field count
Aliases≤ 10 per field—
BatchingCount operationsHTTP-layer limiter
IntrospectionOff in prodSuggestion errors
maxTokensParser-level—
// ✅ Count operations, not requests
const ops = Array.isArray(body) ? body.length : 1;
await limiter.consume(`user:${userId}`, ops);
// Batched mutations are a stuffing vector
if (Array.isArray(body) && body.some(o => /^\s*mutation/.test(o.query))) return 400;

Secrets Management

RuleImplementation
Never in git.gitignore + push protection
Never in the promptMove to code
Runtime injectionVault, AWS Secrets Manager, Doppler
CI → cloudOIDC federation, no long-lived key
Rotation90 days or on any suspicion
ScopePer-service, per-environment
LoggingReference, never print; mask transforms are not masked

Leak Remediation Order

1. revoke the credential      ← minutes matter
2. issue a replacement
3. audit provider logs for use
4. git filter-repo + force push
5. enable push protection
# Remove a file from all history (rotation comes first)
git filter-repo --path config/secrets.yml --invert-paths --force
git push --force --all && git push --force --tags

# Scan full history, redacted output
gitleaks detect --log-opts="--all" --redact --report-format sarif
trufflehog git file://. --only-verified

Supply Chain

ControlCommandProtects
Reproducible installnpm ciLockfile drift
Block lifecycle scriptsnpm ci --ignore-scriptspostinstall RCE
Build allowlistpnpm.onlyBuiltDependenciesScript RCE
Runtime auditnpm audit --omit=dev --audit-level=highKnown CVE
Signature checknpm audit signaturesTarball substitution
Force transitiveoverridesUnpatched deep dep
Provenancenpm publish --provenanceSource↔tarball
SBOM@cyclonedx/cyclonedx-npmInventory
Image signcosign signSubstitution
SRIintegrity="sha384-…"CDN compromise
StandardIdentifier
SBOM formatSPDX (ISO/IEC 5962:2021)
SBOM formatCycloneDX (ECMA-424)
ProvenanceSLSA Build L1 / L2 / L3
SigningSigstore: Fulcio + Rekor
SRI coveragescript, stylesheet, preload only — not fetch, XHR, import()

CI/CD Hardening

# Default deny; every grant deliberate
permissions:
  contents: read

jobs:
  test:
    steps:
      # SHA-pinned; a tag can be moved, a SHA cannot
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with: { persist-credentials: false }

      # Untrusted context through env, never interpolated into the script
      - env: { PR_TITLE: "${{ github.event.pull_request.title }}" }
        run: echo "PR title is $PR_TITLE"

  deploy:
    environment: production          # human approval gate
    permissions: { contents: read, id-token: write }
RiskRule
Script injection${{ }} never inside run; pass via env
pull_request_targetNever check out fork head
Tag mutationPin full commit SHA
Token in .git/configpersist-credentials: false
Cache poisoningKey includes ref
Artifact theftScope run-id
Long-lived cloud keyOIDC with constrained sub

AI / LLM Security

LayerControl
InjectionTool-free read phase; separate act phase
Output → HTMLDOMPurify allowlist
Output → markdownskipHtml, drop images
Output → URLHost allowlist
Output → shell/SQLargv array, parameterise
ExfiltrationCSP img-src / connect-src
ToolsPer-user OAuth, per-tool scope
Irreversible actionConfirm over raw JSON args
Consumptionmax_tokens, loop ceiling, call cap
PromptNo secrets — assume extraction
THE LETHAL TRIFECTA

  [1] private data  +  [2] untrusted content  +  [3] egress
  ─────────────────────────────────────────────────────────────
  remove any one of the three and the injection has
  nowhere to go. Two are survivable; all three are not.
DefenceRobustness
Instruction hierarchyProbabilistic
Prompt delimitersWeak
Output sanitisationStrong
CSP / egress allowlistStrong
Least-privilege scopeStrong
Human confirmationStrong
MonitoringDetective

Threat Modeling — STRIDE

LetterThreatPropertyControl
SSpoofingAuthenticationMFA, mTLS
TTamperingIntegritySignatures, TLS
RRepudiationNon-repudiationAudit log, hash chain
IInfo disclosureConfidentialityAuthz, encryption
DDoSAvailabilityRate limits, quotas
EElevationAuthorizationScope checks
STRIDE PER DFD ELEMENT

  element          S    T    R    I    D    E
  ─────────────────────────────────────────────
  external entity  ✓    ·    ✓    ·    ·    ·
  process          ✓    ✓    ✓    ✓    ✓    ✓
  data store       ·    ✓    ✓    ✓    ✓    ·
  data flow        ·    ✓    ·    ✓    ✓    ·

  Shostack's four questions: building / wrong / doing / good job

Security Testing

TechniqueRuns OnFindsTool
Unit / typesEvery commitLogic errorsjest, tsc
SASTPR diffTainted flowsSemgrep, CodeQL
SCAPRKnown CVEsDependabot, Trivy
DAST baselinePreviewRuntime misconfigZAP passive
DAST fullStaging onlyInjectionsZAP active
FuzzingContinuousParser/memorylibFuzzer, Atheris
Pen testQuarterlyBusiness logicManual
# Passive only — safe against preview
zap-baseline.py -t "$PREVIEW_URL" -J report.json -w report.md

# Active — disposable environments only
zap-full-scan.py -t "$STAGING_URL"

# SAST with SARIF so findings annotate the diff
semgrep ci --sarif --output=semgrep.sarif
// ✅ Fuzz target: any parse success must not panic
f.Add("filter=status:open")
f.Fuzz(func(t *testing.T, raw string) {
    q, err := ParseQuery(raw)
    if err != nil { return }
    _ = q.String()
})

Audit Logging

FieldRequiredPurpose
ts✅Timeline
event✅Classification
outcome✅Attempt vs success
actor.id✅Attribution
actor.ip✅Source
target.id✅Impact scope
request.id / trace_id✅Join to app logs
Never LogWhy
PasswordsAny hash is crackable
Session tokens / API keysReplay
Full PANPCI DSS 3.3; truncate to last 4
CVVPCI DSS — never stored at all
PII beyond purposeGDPR minimisation
// ✅ Hash-chain append: removal is detectable
const body = JSON.stringify({ ...record, prev_hash: prev });
const hash = createHash("sha256").update(body).digest("hex");
await auditSink.append({ ...record, prev_hash: prev, hash });

// ✅ Enumeration detection
// SELECT actor->>'id', count(*) FROM audit_events
// WHERE event='invoice.read' AND outcome='denied'
// AND ts > now() - interval '15 minutes'
// GROUP BY 1 HAVING count(*) > 20;
Retention DriverFloor
PCI DSS 10.5.112 months, 3 online
HIPAA6 years
SEC 17a-46 years
GDPRNo longer than necessary

Incident Response

SeverityDefinitionResponse
SEV1Confirmed breach of customer data / full outagePage, IC, exec in 30 min
SEV2Exploitable in prod, no evidence of usePage, fix in 24 h
SEV3Degraded control, no exposureSprint
SEV4Non-prod / defence-in-depthBacklog
PhaseAction
PrepareOn-call, out-of-band comms, break-glass, evidence procedure
DetectSIEM, WAF, cloud logs, EDR, third-party report
ContainRevoke sessions → rotate keys → block edge → flag off → take down
EradicatePatch the vector, not the symptom; rotate all reachable creds
RecoverVerify against the original detection; watch for recurrence
ReviewBlameless, timeline from logs, contributing factors, owned actions

Notification Deadlines

RegimeDeadlineStarts From
GDPR Art. 3372 hAwareness
GDPR Art. 34Without undue delayHigh-risk confirmation
NIS224 h / 72 h / 1 moAwareness
SEC Item 1.054 business daysMateriality
HIPAA60 daysDiscovery
PCI DSSPromptlyDiscovery
INCIDENT TIMELINE

  T+0     aware
  T+3m    SEV1 declared, IC assigned
  T+14m   counsel engaged      ← legal clock running
  T+22m   containment: revoke sessions, rotate key
  T+1h    snapshot disk + export audit range
  T+6h    vector patched, service restored
  T+72h   GDPR supervisory-authority deadline
  T+7d    blameless post-mortem, owned actions

Quick Commands

# Dependencies
npm ci --ignore-scripts --no-audit
npm audit --omit=dev --audit-level=high
npm audit signatures
npm explain lodash

# Secrets
gitleaks detect --log-opts="--all" --redact
trufflehog git file://. --only-verified
git filter-repo --path secrets.yml --invert-paths --force

# Artifacts
npx @cyclonedx/cyclonedx-npm --omit dev > sbom.json
syft packages registry/app@sha256:abc -o spdx-json
cosign sign registry/app@sha256:abc
cosign verify registry/app@sha256:abc --certificate-oidc-issuer <issuer>
npm publish --provenance

# Integrity
openssl dgst -sha384 -binary lib.js | openssl base64 -A

# TLS
openssl s_client -connect example.com:443 -tls1_3 -servername example.com
testssl.sh --severity HIGH example.com

# Testing
semgrep ci --sarif --output=semgrep.sarif
zap-baseline.py -t "$PREVIEW_URL"
go test -fuzz=FuzzParseQuery -fuzztime=60s

The Request Pipeline

┌────────────────────────────────────────────────────┐
│  INCOMING REQUEST                                  │
│      │                                             │
│      ▼                                             │
│  [1] Edge limiter      coarse, per-IP, volumetric  │
│      │                                             │
│      ▼                                             │
│  [2] Authenticate      token, key, or session      │
│      │                                             │
│      ▼                                             │
│  [3] Scope check       default deny                │
│      │                                             │
│      ▼                                             │
│  [4] Identity limit    per account, proxy-proof    │
│      │                                             │
│      ▼                                             │
│  [5] Object authz      ownership in the query      │
│      │                                             │
│      ▼                                             │
│  [6] Input validation  schema, allowlist           │
│      │                                             │
│      ▼                                             │
│  [7] Handler           the only code with data     │
│      │                                             │
│      ▼                                             │
│  [8] Audit record      actor, target, outcome      │
└────────────────────────────────────────────────────┘

The Defence Stack

┌────────────────────────────────────────────────────┐
│  LAYER              STOPS              ROBUSTNESS  │
│  ─────────────────────────────────────────────────  │
│  authz               BOLA, BFLA        strong      │
│  validation          injection         strong      │
│  output encoding     XSS               strong      │
│  CSP / egress        exfiltration      strong      │
│  least privilege     blast radius      strong      │
│  rate limit          volume            moderate    │
│  bot score           automation        probabilistic│
│  WAF                 known patterns    weak        │
│  monitoring          detection only    detective   │
└────────────────────────────────────────────────────┘

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!