Skip to content
Tech Interview Prep
Technical interview guide

Common Web Vulnerabilities (OWASP Top 10)

The most common web application security risks, and the concrete pattern behind each one.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: OWASP Top 10:2025 and OWASP Cheat Sheet Series guidance accessed 2026-08-31..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

What is the OWASP Top 10, and how should an engineering team use the 2025 edition?

Answer

What it is, and the 90-second answer

The OWASP Top 10 is a consensus awareness document: a ranked list of the most critical web application security risks, built from contributed testing data and a practitioner survey. It is not a standard, not a certification, and not a risk ranking for your system. The 2025 edition is a release candidate; treat the ordering as provisional until it is final.

I use it as an input to threat modeling, not as a test plan. Concretely: map each category to my assets, data flows and trust boundaries; derive testable invariants from the ones that apply; use ASVS for the depth the Top 10 deliberately omits; and prioritize by local exposure, exploitability and blast radius rather than by category number.

What changed in 2025

The headline shifts from the 2021 edition: software supply chain failures became their own category (previously folded into vulnerable and outdated components), and mishandling of exceptional conditions was added. Broken access control stayed at the top. The release-candidate ordering:

#2025 category
A01Broken Access Control
A02Security Misconfiguration
A03Software Supply Chain Failures
A04Cryptographic Failures
A05Injection
A06Insecure Design
A07Authentication Failures
A08Software and Data Integrity Failures
A09Logging and Alerting Failures
A10Mishandling of Exceptional Conditions

How to use it without fooling yourself

Map each category to a testable invariant and a detection signal, not a ticket:

CategoryInvariantDetection
A01 Broken Access ControlEvery endpoint enforces object ownership server-sideRequest user B's token for user A's object → 403/404
A03 Supply ChainBuilds resolve from a pinned lockfile with provenanceCI fails on unpinned or unsigned dependency
A10 Exceptional ConditionsUnhandled exceptions return a generic error and log a correlation IDNegative tests: no stack traces in responses

Failure modes

Checklist substitution. Ten tickets, one per category, closed and declared done. Broken access control alone spans IDOR, missing function-level checks, CORS misconfiguration and forced browsing; one ticket covers a fraction. Detect it by comparing ASVS L2 requirements covered against Top 10 categories: a ratio near 10:1 means you tested the label, not the risk. Cost: the same class reappears in the next pentest.

Number-order prioritization. Fixing A01 first because it is #1 while your real exposure is A03: say 1,200 transitive dependencies in the build. Detect it by comparing your dependency-CVE backlog and last three incidents against the ordering; if the incidents were supply chain and the quarter went to access control, the ordering is misaligned.

Compliance framing. "We're OWASP Top 10 compliant": no such certification exists. Detect it when a customer asks for the certificate, or when a control maps to a category but has no test behind it.

Stale mapping. A control set built on the 2021 edition has no owner for supply chain or exceptional conditions. Diff your controls against the 2025 list; unmapped categories are gaps.

Prioritizing (hypothetical figures)

Score each applicable category as exposure × exploitability × blast radius, each 0–3. Supply chain (3×2×3 = 18) outranks access control (2×3×2 = 12) even though access control is A01. The numbers are illustrative; the point is that the list orders the population, not your system.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Prevent injection across SQL, shell, templates, LDAP, and rendered browser content.

Answer

Core answer. Injection is one bug with five faces: untrusted data is concatenated into a string that a parser then reads as syntax. The fix is the same everywhere: keep data out of the syntax channel. Bind parameters for SQL, pass argv arrays instead of shell strings, let a context-aware template engine escape, escape LDAP filters per RFC 4515, and let the framework escape browser output per context. Validation and allow-listing are for the cases where you must insert syntax (identifiers, sort columns, commands); they are not a substitute for separation.

Assumptions: the attacker controls some input that reaches the boundary, and you control the code but not the data.

Why it works. Every interpreter (SQL, sh, Jinja2, LDAP, the HTML parser) has a grammar. Concatenation puts attacker bytes inside that grammar, so ' closes a string literal and ; ends a command. Binding removes the ambiguity: the parser parses the statement first, then the value is attached as an opaque value.

Trace. SQLite, Python 3.12:

Python
name = "' OR '1'='1"
cur.execute(f"SELECT * FROM users WHERE name = '{name}'")
# -> SELECT * FROM users WHERE name = '' OR '1'='1'   -> every row
cur.execute("SELECT * FROM users WHERE name = ?", (name,))
# -> parser sees one statement with one bound parameter -> zero rows

Shell, same idea:

Python
subprocess.run("ls " + user, shell=True)   # user="; rm -rf /tmp/x" -> shell runs both
subprocess.run(["ls", user])               # execve("/bin/ls", ["ls", "; rm -rf /tmp/x"]) -> ENOENT

Per interpreter.

BoundaryDoDon't
SQLPreparedStatement (JDBC), cursor.execute(sql, params) (DB-API), ?/$1 placeholdersf-strings, % formatting; parameters cannot bind table/column names: allow-list those
Shellargv list, subprocess.run([...]), execveshell=True, os.system, backticks
TemplatesJinja2 autoescape (Flask enables it for .html), Go html/template contextual escaping, React JSX text`
LDAPRFC 4515 escaping: \→\5c, *→\2a, (→\28, )→\29, NUL→\00; Spring LdapQueryBuilderstring-built filters
Browsercontext-specific escaping (HTML text vs attribute vs URL vs JS), Content-Security-Policy: script-src 'self'one encoder for all contexts; CSP without 'unsafe-inline' blocks inline handlers

Trade-offs. Parameterization is the default; it fails only when the structure is dynamic: ORDER BY ? is not portable, so allow-list the column against a fixed set. Escaping is the fallback when you must build syntax; it is context-specific and easy to get wrong, so prefer an encoder over hand-rolled. Allow-listing is the right tool for identifiers and commands, wrong for free text. CSP is defense in depth, not a fix: it does not stop server-side SQLi or LDAP injection.

Failure modes. Error-based SQLi shows as parser errors in app logs (sqlite3.OperationalError: near "OR") and 500 spikes; blind/time-based shows as latency outliers with no error. Second-order payloads are stored clean and fire on a later read path: grep reporting/export code for concatenation. Detection: WAF/query-log review, latency histograms, and tests that assert a payload round-trips as data.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How do you harden XML parsing to prevent XML external entity (XXE) and related parser attacks in an application that accepts XML or parses untrusted documents?

Answer

I treat XML as executable configuration, not data. A parser that resolves external entities will fetch URLs, read local files, and expand entities until memory is gone. So the default posture is: no DTDs, no external entities, no external schema, no XInclude, no XSLT document(). Enforced in one hardened factory that every XML path must use.

Concretely, per runtime. Java: DocumentBuilderFactory with disallow-doctype-decl=true, external-general-entities=false, external-parameter-entities=false, load-external-dtd=false, XIncludeAware=false, expandEntityReferences=false, FEATURE_SECURE_PROCESSING=true, and ACCESS_EXTERNAL_DTD/ACCESS_EXTERNAL_SCHEMA set to "". Python: defusedxml, or lxml with resolve_entities=False, no_network=True, load_dtd=False, dtd_validation=False. .NET: XmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit and XmlResolver = null. PHP: LIBXML_NONET and never LIBXML_NOENT; libxml_disable_entity_loader is deprecated in PHP 8 but the default changed. Node: avoid libxmljs with default options; use a parser that does not resolve entities.

Why disallow-doctype-decl is the strongest single control: without a DOCTYPE you cannot declare an external entity, so both file-read and SSRF payloads fail at parse time. If a partner genuinely requires DTDs, fall back to the narrower set plus an EntityResolver returning an empty stream, but that is weaker, because parameter entities echoed in error messages can still exfiltrate.

Related parser attacks: billion laughs and quadratic blowup are entity expansion, so cap total expansion and input size. XInclude can pull files even with DTDs off. XSLT's document() function is an SSRF primitive. SVG, DOCX/XLSX, SAML, SOAP and RSS are all XML surfaces that often get a different parser than your main API. Inventory every one.

Detection: SAST rules for the factory features, dependency scanning for parser versions, and egress monitoring. A blind XXE shows up as a DNS or HTTP request from an app server to an attacker-controlled host. Fuzz with a payload that tries file:///etc/passwd and an out-of-band parameter entity.

Failure mode: a wrapper library re-enables DTDs, or a developer calls newDocumentBuilder() directly. The factory is the only allowed constructor, enforced by a build-time check.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How do you prevent XSS in an application that supports rich user content?

Answer

First 90 seconds

Two things decide the approach: who can post rich content, and where it renders. A comment box for logged-in users and a staff CMS are different problems: a stored payload against a CMS runs in an admin session, so it's account takeover, not a defaced comment. Then ask whether the app needs HTML at all. If "rich" means bold, links and code blocks, store Markdown and render it through an auto-escaping template; there is no sanitizer to bypass.

If I do need untrusted HTML, I treat it as data and never as a template. Anything that isn't markup goes through output encoding chosen for its context; the HTML that must stay HTML goes through an allow-list sanitizer (DOMPurify in the browser, sanitize-html on Node) stored sanitized with the sanitizer version recorded next to it. Trusted Types and a nonce-based CSP sit on top as containment for what gets past, not as the fix.

Why encoding is context-bound

The HTML parser decides what is a tag from its position in the grammar. <img src=x onerror=alert(1)> arriving in a text position is escaped to &lt;img src=x onerror=alert(1)&gt; and becomes a text node: &lt; is an entity, so no element opens. JSX children work the same way: they are text nodes, never concatenated into markup.

HTML escaping only neutralises HTML metacharacters, though. javascript:alert(document.domain) contains none of them, so HTML-escaped into <a href="{{url}}"> it still fires on click. URL contexts need a scheme allow-list before any encoding.

SinkContextRequired
element textHTML textauto-escape & < > " '
href, srcURLallow https:/mailto:, reject javascript: and data:
onclick="{{x}}"JSnot this: addEventListener, value as argument
<style>CSSnot this: fixed class list
innerHTML, dangerouslySetInnerHTMLmarkupsanitizer output only

Sanitizing

A sanitizer is only trustworthy if it parses with the parser the browser will use, walks that tree against an allow-list, and serializes the tree. DOMPurify does this against the real DOM, which is how it survives parser-level tricks; on the server it needs jsdom, a different parser implementation, and server and client results diverge there. sanitize-html ships a limited default tag set with allowedSchemes of http, https, ftp, mailto and tel: ftp and tel are in there by default, and no on* attribute is allowed.

Regex stripping fails on nesting. Remove <script> once from <scr<script>ipt>alert(1)</script> and the fragments join back up into <script>alert(1)</script>, which is what the browser then gets.

The failure mode worth rehearsing is mutation XSS: the sanitizer emits a string, the browser parses it again, and the two trees differ. Entity decoding is the one-way door.

Input: <div title="&quot;&gt;&lt;img src=x onerror=alert(1)&gt;">hi</div>

  1. Parsing decodes entities, so the DOM holds a div whose title value is the literal text "><img src=x onerror=alert(1)>. title is on every sane allow-list, so the attribute survives.
  2. If the serializer writes that value back with a template literal, the output is <div title=""><img src=x onerror=alert(1)>">hi</div>.
  3. The browser's next parse ends the attribute at the second ", and the <img> is now a real element with an onerror handler.

Never hand-build the output string: serialize the node (outerHTML, or DOMPurify's default string return), which re-escapes &, <, > and " inside attribute values. Test with an entity round-trip corpus plus SVG and MathML, not just <script>.

Containment

Content-Security-Policy: script-src 'nonce-{random}' 'strict-dynamic'; object-src 'none'; base-uri 'none'

Nonces make injected inline <script> inert; 'strict-dynamic' makes CSP3 browsers ignore host allow-lists, so a CDN entry kept "just in case" does nothing. Deploy it Report-Only first: the violation reports are the payloads that got past the sanitizer. Trusted Types (require-trusted-types-for 'script') turns a bare innerHTML = string into a runtime error unless the value came from a policy; DOMPurify can return a TrustedHTML through its own dompurify policy. Neither contains a payload that already got through, and neither stops cross-site requests acting as the user: HttpOnly makes document.cookie unreadable, but fetch('/api/transfer', {credentials:'include'}) still carries the session, so CSRF tokens or SameSite=Lax stay.

One assumption to state out loud: sanitize on write, since feeds, emails, exports and search snippets all render that content; re-sanitize on read when the stored sanitizer version predates the deployed one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design broken-access-control defenses for a multi-tenant SaaS API.

Answer

First 90 seconds

Clarify: assume every owned row already carries a tenant_id, and that an authoritative store knows memberships and roles. This is an enforcement problem, not an identity one. In the OWASP API Security Top 10 2023 that is API1 Broken Object Level Authorization, API5 Broken Function Level Authorization, and API3 Broken Object Property Level Authorization: the object, the function, the field.

Core answer: make the tenant part of the query, not part of the request. The server derives subject and tenant from verified session state, holds them in a request-scoped context, and every read and write runs inside a transaction that stamps that context into the database session. Nothing the client sends (userId, role, tenant_id in body, query or path) is merged into that context; it is at most compared and rejected. Above the rows, a policy decision point covers what a row filter cannot express: relationships (is u17 the approver on this invoice), state (can a paid invoice be voided), fields (can this role see amount_cents but not bank_account). The same context has to thread through list and search, bulk and nested routes, file downloads, exports, GraphQL resolvers and background jobs: those secondary paths are where the check gets forgotten.

Artefact: row filter and trace

SQL
-- PostgreSQL 15
ALTER TABLE invoice ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoice FORCE ROW LEVEL SECURITY;   -- binds the table owner too

CREATE POLICY tenant_isolation ON invoice
  USING      (tenant_id = current_setting('app.tenant_id', true)::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);
SQL
BEGIN;
SELECT set_config('app.tenant_id', $1, true);   -- $1 from context, never from the request
SELECT id, amount_cents FROM invoice WHERE id = $2;
COMMIT;

Trace GET /v1/invoices/42?tenant_id=T-B with a token for u17 in tenant T-A:

  1. Token verified against the issuer JWKS; context is {subject: u17, tenant: T-A}. The parameter tenant_id=T-B is dropped, not merged.
  2. $1 = 'T-A', $2 = 42. The policy USING clause is appended to the scan, so the row owned by T-B never leaves the heap.
  3. Zero rows, so the handler returns 404 rather than 403: a guessing client learns nothing about which IDs exist.
  4. With app.tenant_id unset, current_setting(..., true) returns NULL, the comparison is NULL, and the result is still zero rows.

This buys two things: a route added next quarter that forgets its own check still cannot read across tenants, and FORCE ROW LEVEL SECURITY binds the table owner as well. It costs two: filtering is silent, so probing produces no error signal. Alert on 404s per token; and the stamp is transaction-scoped, which is exactly why it survives connection pooling. A session-level SET on a pooled connection can leak one tenant into the next request, and that is the first thing I would grep for in an existing codebase.

Alternatives and when each wins

A centralised PDP: OPA serving Rego bundles, or Cedar as the engine behind Amazon Verified Permissions: puts every rule in one place: unit-testable, with per-decision logs and an explainable answer. The cost is a new failure domain plus a decision cache that goes stale on revocation, so a removed approver keeps approving until the TTL expires; keep membership TTLs short and role definitions longer. Query-scoped repositories with RLS have no extra hop and decide inside the engine, but they only express row-shaped tenancy inside one database. Centralised wins when many services share relationship-heavy rules; scoped queries win when one service owns the rows and latency matters. Most systems run both, database last, because policies that live only in application code are the ones that regress.

Scale arithmetic, illustrative: at 1.5 ms p99 per PDP call, a list page fanning out to 240 objects costs 360 ms if you call per object. Batch it into one decision query carrying the object list, or keep the list on the row filter and call the PDP only for field redaction on the returned page.

Failure modes

Fail-open: the PDP is down, or someone adds a catch-all allow rule. Default deny on outage, and have CI assert a known cross-tenant request is denied. Privileged bypass: a background worker connecting as a superuser or a BYPASSRLS role reads everything. Give workers their own role and alarm if a request-serving role ever gains BYPASSRLS. Admin impersonation is the recurring hole; carry the impersonating actor in the request context and in the audit row.

What would change this: physically sharding tenants so the database boundary does the isolation, with RLS as belt and braces; or letting tenants share objects, at which point a single tenant_id column stops being the model and a relationship graph, Zanzibar-style tuples, has to become the decision source.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Threat-model and defend a server-side URL fetcher against SSRF.

Answer

First 60 seconds. Before designing anything I ask whether arbitrary fetching is actually the requirement. If the product calls a fixed set of third-party APIs, I delete the fetcher and replace it with a brokered integration: a server-side allow-list of hostnames and path prefixes, no user-controlled host at all. That removes the vulnerability class rather than mitigating it. Assume the answer is yes: arbitrary URLs are the feature, and the fetcher runs in a VPC that can reach cloud metadata and internal services. Then the job is to constrain four things in order: scheme, destination, resolution, and egress.

1. Parse once, canonically. urllib.parse.urlsplit in Python 3.11+. Allow http and https only, which kills file://, gopher://, dict://, ftp:// and jar://. Reject userinfo (http://expected.com@evil.com/), reject any port other than 80 or 443. Do not validate the hostname string: validate the IP it resolves to. That is what catches http://2130706433/ and http://0x7f.1/, because the check runs on the resolved address, not on the text.

2. Resolve, check, then connect to the pinned IP. This is the part that matters. socket.getaddrinfo returns every A and AAAA record; check all of them, not just the first. Then connect to the address you checked, with the Host header and TLS SNI set to the original hostname. Why: if you hand the hostname to requests/urllib3, it resolves a second time at connect. An attacker with a 0-TTL record answers the first query with a public IP and the second with 127.0.0.1. That is DNS rebinding, and it is a check-then-use gap, not a parsing bug.

Python
# Python 3.11+
import ipaddress, socket
from urllib.parse import urlsplit

BLOCKED = [ipaddress.ip_network(n) for n in (
    "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8",
    "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.168.0.0/16",
    "198.18.0.0/15", "224.0.0.0/4", "240.0.0.0/4",
    "::/128", "::1/128", "fc00::/7", "fe80::/10", "ff00::/8",
)]

def pin(url):
    u = urlsplit(url)
    if u.scheme not in ("http", "https"):
        raise ValueError("scheme")
    if u.username or u.password:
        raise ValueError("userinfo")
    port = u.port or (443 if u.scheme == "https" else 80)
    if port not in (80, 443):
        raise ValueError("port")
    infos = socket.getaddrinfo(u.hostname, port, type=socket.SOCK_STREAM)
    for family, _, _, _, sockaddr in infos:
        ip = ipaddress.ip_address(sockaddr[0])
        if ip.version == 6 and ip.ipv4_mapped:
            ip = ip.ipv4_mapped          # ::ffff:127.0.0.1 -> 127.0.0.1
        if any(ip in net for net in BLOCKED):
            raise ValueError(f"blocked {ip}")
    return infos[0][4]                    # connect to THIS address

Trace. pin("http://evil.com/x"): scheme http, hostname evil.com, port None → 80. getaddrinfo hits the attacker's DNS, which answers 93.184.216.34; the loop checks IPv4Address('93.184.216.34') against every net, finds no match, and returns ('93.184.216.34', 80). The caller does socket.create_connection(('93.184.216.34', 80)). Had the caller instead called requests.get("http://evil.com/x"), urllib3 would call getaddrinfo again at connect time; the attacker's DNS, now answering 127.0.0.1, sends the request to loopback and pin never sees it.

3. Redirects. requests follows up to 30 by default. Set allow_redirects=False and loop yourself, max 5 hops, running pin on every hop. Otherwise hop 2 is unchecked. Continuing the trace: the attacker's server at 93.184.216.34 replies 302 Location: http://169.254.169.254/latest/meta-data/iam/security-credentials/. The loop calls pin on that URL, getaddrinfo returns ('169.254.169.254', 80), and ipaddress.ip_address('169.254.169.254') in ipaddress.ip_network('169.254.0.0/16') is True: ValueError: blocked 169.254.169.254. The request never leaves.

4. Egress, independently. A validator has bugs. Run the fetcher in a subnet whose security group or Kubernetes NetworkPolicy permits only the destinations it needs, and give the process no IAM role. Then metadata is unreachable even if pin is wrong.

CloudMetadata endpointHeader required
AWS IMDSv1http://169.254.169.254/latest/meta-data/none
AWS IMDSv2samePUT /latest/api/token, X-aws-ec2-metadata-token-ttl-seconds: 21600
GCPhttp://metadata.google.internal/computeMetadata/v1/Metadata-Flavor: Google
Azurehttp://169.254.169.254/metadata/instanceMetadata: true

IMDSv2 and the GCP/Azure headers mean a naive GET-based SSRF returns 401 rather than credentials: enforce IMDSv2 on every instance, because it is the cheapest control here.

5. Response handling. Connect timeout 2 s, read timeout 5 s, body capped at 1 MiB, content types limited to text/* and application/json. Errors return a generic 502 with no internal hostname or stack trace.

Detection. Log the hostname and the resolved IP, not the full URL: URLs carry tokens. Alert on every blocked-destination event; a single one is a live probe, not noise.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How do you prevent and detect security misconfiguration across cloud and application environments?

Answer

Core answer (first 90 seconds)

Prevention is one thing: make the secure configuration the only configuration that can ship. I keep baselines as versioned code: Terraform for cloud, Helm/Kustomize for Kubernetes, a hardened base image for containers, and gate them in CI with policy-as-code. Detection is the other half: assume something will drift, so I run a CSPM tool continuously against effective state, not against the repo.

Concretely the pipeline is: terraform plan → OPA/Conftest or Checkov → merge → deploy → AWS Config, Security Hub and GuardDuty watch the running account → drift alert routed to the owning team by resource tag.

Why policy-as-code, not a checklist

A checklist rots; a Rego rule fails the build. Example: deny any security group with 0.0.0.0/0 on port 22, evaluated against terraform show -json output:

REGO
package terraform.aws

deny[msg] {
  resource := input.resource_changes[_]
  resource.type == "aws_security_group"
  rule := resource.change.after.ingress[_]
  rule.cidr_blocks[_] == "0.0.0.0/0"
  rule.from_port <= 22
  rule.to_port >= 22
  msg := sprintf("SG %s exposes SSH to the internet", [resource.name])
}

That runs in seconds on a 500-resource plan and blocks the merge. A human reviewing the same plan is slower and inconsistent: they catch the obvious open port and miss the one buried in a module.

Detection: effective state, not declared state

The gap that bites is console changes. Someone flips an S3 bucket public in the console; Terraform never sees it. AWS Config's s3-bucket-public-read-prohibited managed rule fires on the config change, Security Hub aggregates the finding, and it routes to the bucket's owner tag. New S3 buckets have shipped with Block Public Access on by default since April 2023, but pre-existing buckets and cross-account replication don't inherit that, so the rule still earns its keep.

For runtime, GuardDuty covers credential misuse and crypto-mining. For containers, Kubernetes Pod Security Admission's restricted profile (stable since 1.25) rejects privileged pods at admission time, before they ever schedule.

Trade-offs

Strict baselines slow teams down. Three options, and when I pick each:

ApproachShip latencyCoverageWhen to pick
Blocking CI gate+2–5 min per PRDeclared config onlyDefault for IaC-managed resources
Advisory scan0Declared + driftLegacy accounts you can't gate yet
Runtime admission0Effective stateKubernetes, where drift is constant

I gate IaC-managed resources and lean on admission control where drift is the norm. Exceptions get an owner, a compensating control, and a 90-day expiry: otherwise the exception list quietly becomes the new baseline.

Failure modes

  1. Drift goes undetected. Signal: a resource type exists in the account with no matching Config rule. Cost: a public bucket sits for weeks. Fix: coverage dashboard that alerts when a new resource type appears without a rule.
  2. Policy passes but the deployed artifact differs. Signal: image digest in prod ≠ digest that passed CI. Cost: a patched CVE ships anyway. Fix: sign images with cosign, verify the digest at admission.
  3. Alert fatigue. Signal: hundreds of findings a day with no owner tag. Cost: real findings buried. Fix: route by tag, auto-close on remediation, track mean-time-to-remediate.

Rollback

Config rollback has to restore dependent policy too: reverting a security group without its NACL leaves a hole. I re-apply the last-known-good Terraform state rather than hand-editing, so the change is reviewable and reproducible.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Design cryptographic protection for sensitive application data.

Answer

Assumptions first. I'll assume a multi-tenant SaaS storing PII and payment-adjacent data, running on a cloud provider with a managed KMS, under GDPR plus PCI DSS. If the threat model were only "stolen disk," the answer collapses to full-disk encryption and I'd say that in the first sentence.

Core answer. Encrypt at the layer that matches the threat, keep keys in a hierarchy, and make every ciphertext self-describing.

Threat → layer:

  • Stolen disk or decommissioned volume → full-disk encryption (LUKS, cloud EBS encryption).
  • DB dump, backup exfiltration, over-broad DBA access → field-level encryption in the application, before the database sees plaintext.
  • Network interception → TLS 1.3 with certificate validation; mTLS between internal services.
  • Queues and backups → the same envelope scheme as the database, not a second one.

Field-level is the one that costs you: encrypted columns can't be range-queried or indexed normally. Equality search needs deterministic encryption (AES-SIV) or a blind index (HMAC-SHA-256 of the normalized value), and both leak frequency. That trade-off is the thing to say out loud.

Key hierarchy. Root key lives in KMS and never leaves. A per-tenant data encryption key (DEK) is generated locally, wrapped by the root key, and stored beside the ciphertext. Envelope encryption exists because KMS Encrypt caps plaintext at 4 KB and is quota-limited per second: you cannot call it per row.

Python
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os

def seal(dek: bytes, plaintext: bytes, aad: bytes) -> bytes:
    nonce = os.urandom(12)              # 96-bit, fresh per message
    ct = AESGCM(dek).encrypt(nonce, plaintext, aad)
    return b"\x01" + nonce + ct         # 0x01 = key/algorithm version

AESGCM.encrypt returns ciphertext with a 16-byte tag appended, so the blob is 1 + 12 + len(pt) + 16 bytes. The AAD binds the ciphertext to its tenant and field name, so a row can't be moved between tenants.

The failure that matters: nonce reuse. GCM with a repeated nonce under the same key leaks the XOR of the two plaintexts and lets an attacker forge tags. With random 96-bit nonces, NIST SP 800-38D caps you at 2^32 invocations per key: collision probability is roughly q²/2^97, about 2^-33 at that limit. Two fixes: rotate the DEK well before 2^32 messages, or use AES-GCM-SIV (RFC 8452) or XChaCha20-Poly1305, which tolerate nonce reuse. Detect it by counting encryptions per key and alerting at a threshold.

Passwords are hashed, not encrypted: Argon2id at OWASP's minimum (m=19 MiB, t=2, p=1) or bcrypt cost 12. Store the parameters with the hash so you can raise them later.

Crypto-agility. Every blob carries a version byte, as above. Rotation is: write the new version, re-wrap DEKs, lazily re-encrypt rows. Test that a restore from a six-month-old backup still decrypts with the old key version still present in KMS.

Failure modes and detection:

  • Key compromise → KMS audit logs (CloudTrail) show unexpected Decrypt calls; alarm on volume.
  • Rotation half-done → rows carry mixed versions; a nightly job counts the version distribution.
  • Backup restore against a deleted key → quarterly restore drill, not an incident-time discovery.
  • Partial failure → one tenant's DEK unavailable; per-tenant keys keep the blast radius to that tenant.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do you store and migrate user passwords safely?

Answer

What I'd say first (60–120s)

Assumptions: I own the auth service, I have a KMS/HSM for secrets, and I can't force every user to reset. The answer is Argon2id with the parameters stored inside each hash string, rehash-on-login when policy advances, and a versioned pepper held in the KMS.

Concretely: Argon2id at m=19456 KiB (19 MiB), t=2, p=1, OWASP's minimum, with a 16-byte random salt per password. Store the full encoded string, e.g. $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>. Never store plaintext or a reversible encryption of it.

Why it works

Salts defeat rainbow tables and make identical passwords hash differently, so cracking one doesn't unlock N accounts. Argon2id's memory hardness is the point: every guess must allocate 19 MiB, so a GPU that runs millions of SHA-256/s drops to thousands/s, and ASICs get no cheap win. t=2 and p=1 tune CPU passes and lanes; raise m before t if you have RAM headroom.

Rehash-on-login works because you hold the plaintext only at that moment. Verify against the params embedded in the stored string, then if check_needs_rehash says policy moved, hash again and overwrite. Users migrate as they log in; no mass reset.

Alternatives

bcrypt cost 12 is battle-tested, but it truncates at 72 bytes: pre-hash with SHA-256 then base64 if you allow long passphrases. scrypt (N=2^17, r=8, p=1) is memory-hard too but harder to tune. PBKDF2-HMAC-SHA256 at 600,000 iterations is the FIPS fallback; it isn't memory-hard, so GPUs do better against it. Use Argon2id unless a compliance regime forces PBKDF2.

Migration and pepper

Pepper is an HMAC key in the KMS applied to the password before hashing. Store a pepper version ID in the record so you can rotate: verify with v1, rehash with v2 on next login. If the pepper is lost and unversioned, every hash is unverifiable: that is the one case where forced reset is correct. Same for a hash algorithm you can no longer verify.

Failure modes and detection

  • Pepper outage: 100% of logins fail at once. Detect via an auth success-rate alert; keep the old key readable during rotation.
  • DoS via hashing: 19 MiB × concurrent logins exhausts RAM. Detect p99 login latency and RSS; cap concurrent verifications with a semaphore.
  • Enumeration timing: unknown user returns in ~1 ms, known user in ~80 ms. Detect by timing both paths; run a dummy hash on the miss path.
  • bcrypt truncation: two 80-byte passwords collide. Detect with a 73-byte test vector.

Code (Python 3.12, argon2-cffi 23.1)

Python
from argon2 import PasswordHasher, Type
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1,
                    hash_len=32, salt_len=16, type=Type.ID)

def register(pw: str) -> str:
    return ph.hash(pw)

def login(pw: str, stored: str) -> tuple[bool, str | None]:
    try:
        ph.verify(stored, pw)          # uses params embedded in `stored`
    except VerifyMismatchError:
        return False, None
    if ph.check_needs_rehash(stored):
        return True, ph.hash(pw)       # caller persists the new hash
    return True, None

Trace: register("hunter2") returns $argon2id$v=19$m=19456,t=2,p=1$<16B salt>$<32B hash>. login parses m,t,p from that string, so a hash written under m=9216 still verifies; check_needs_rehash returns True only when the stored params differ from ph's, which is what drives the migration.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design secure authentication and session lifecycles for a consumer web application.

Answer

I'd start by clarifying the risk profile: this is a consumer web app, so the main threats are credential stuffing, phishing, session theft, and account takeover. I'd assume we need NIST SP 800-63B AAL2 for most users, with AAL3 for high-value actions like changing payout details. My core recommendation: make WebAuthn the primary authenticator, keep passwords as a fallback with breached-password checks, and use server-side sessions with 128-bit IDs, 30-minute idle timeout, and 12-hour absolute timeout.

WebAuthn binds a public key to the origin, so a phishing site can't replay the credential. Passwords are checked against HIBP's Pwned Passwords range API using k-anonymity: we send the first 5 characters of the SHA-1 hash and check the returned suffixes. Hashing uses Argon2id with m=19 MiB, t=2, p=1 (OWASP 2023), or bcrypt cost 12 if Argon2 isn't available. We allow passwords up to 64 characters, no composition rules, and no forced rotation.

Sessions are stored server-side. We store SHA-256 of the session ID, not the ID itself, so a database leak doesn't yield usable sessions. The cookie uses the __Host- prefix, Secure, HttpOnly, SameSite=Lax, Path=/. We rotate the session ID on login and on any privilege change (password, MFA, email). Idle timeout is 30 minutes, absolute 12 hours. Logout deletes the server-side row and clears the cookie. On account deletion, we cascade-delete sessions, tokens, and PII.

For MFA, WebAuthn is best, then TOTP, then push with number matching. SMS is a last resort because of SIM swap. For sessions, stateless JWTs scale but revocation is hard; if you use them, keep them short-lived (5 min) with refresh token rotation and a revocation list. Don't use long-lived JWTs without revocation.

Failure modes and detection:

  • Session fixation: rotate on login. Detect by monitoring session ID changes.
  • CSRF: SameSite=Lax blocks cross-site POST, but for state-changing requests use a double-submit token. Detect via CSRF token mismatch logs.
  • MFA fatigue: rate-limit push notifications (e.g., 5 per 10 min), use number matching, lock after 5 failures. Detect via push response times and failure counts.
  • Recovery downgrade: require the same assurance for recovery as login, use single-use recovery codes (10 codes, hashed), never security questions. Detect via recovery code usage alerts.
  • Enumeration: constant-time responses, generic errors, and dummy hash verification to equalize timing. Detect via timing analysis.
  • DoS via lockout: use exponential backoff (1s, 2s, 4s... up to 15 min), not permanent lockout. Detect via failed login rate spikes.

Here's a session parameter table and a rotation snippet (Python 3.12):

ParameterValueRationale
Session ID entropy128 bits from secrets.token_urlsafe(16)Brute-force infeasible
Cookie attributes__Host- prefix, Secure, HttpOnly, SameSite=Lax, Path=/Prevents subdomain injection, XSS theft, CSRF
Idle timeout30 minBalances usability and risk
Absolute timeout12 hLimits stolen session lifetime
RotationOn login, privilege change, and every 15 minMitigates fixation and replay
Server-side storeSHA-256 of session IDDB leak doesn't yield usable sessions
InvalidationDelete row on logout, password change, or admin actionImmediate revocation
Python
import secrets, hashlib, time

def new_session(user_id, db):
    sid = secrets.token_urlsafe(16)  # 128 bits
    sid_hash = hashlib.sha256(sid.encode()).hexdigest()
    db.execute(
        "INSERT INTO sessions (sid_hash, user_id, created_at, last_seen, absolute_expires) "
        "VALUES (?, ?, ?, ?, ?)",
        (sid_hash, user_id, time.time(), time.time(), time.time() + 12*3600)
    )
    return sid

def rotate_session(old_sid, user_id, db):
    old_hash = hashlib.sha256(old_sid.encode()).hexdigest()
    db.execute("DELETE FROM sessions WHERE sid_hash = ?", (old_hash,))
    return new_session(user_id, db)

That's the core. The trade-off I'd change under different risk: if the app were a bank, I'd drop SMS entirely, require WebAuthn for all users, and shorten idle timeout to 5 minutes. For a low-risk social app, I might allow SMS and longer timeouts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do you design rate limiting, lockout, and anti-automation controls so that credential stuffing, password spraying, and account or identifier enumeration are prevented without locking out legitimate users?

Answer

I'd split the problem before picking controls, because credential stuffing, spraying and enumeration fail against different defenses.

Assume a consumer app with email+password, ~10M accounts, Redis available, and a CDN/WAF in front.

Enumeration is a response-shape problem, not a rate problem. Unknown and known accounts must return identical status, body and latency. That means hashing the submitted password against a fixed dummy bcrypt hash when the user doesn't exist: otherwise unknown returns in 3 ms and known in 90 ms, and the timing alone enumerates the user base. Same rule for registration ("if that address is free we've emailed you"), password reset, and any "email already in use" error. Rate limiting never fixes a differential response.

Layer counters on independent dimensions, and never hard-lock the account. A hard lockout is itself the DoS: an attacker locks 50,000 accounts by submitting five wrong passwords each. Escalate friction instead.

KeyWindowThresholdAction
account+IP15 min5 failuresCAPTCHA
account (global)1 h20 failuresstep-up: emailed link or MFA, not lockout
IP5 min20 auth attempts429 with Retry-After
IP, distinct usernames10 min10challenge + flag
ASN / /241 h200 distinct accountsalert, raise challenge rate

The account+IP pair is the primary key: it stops one attacker grinding a single account without punishing a user who mistyped on a shared office NAT. Per-IP limits are secondary, because CGNAT and mobile carriers put thousands of legitimate users behind one address.

Stuffing defeats IP limits by design. 100,000 attempts spread over 5,000 residential proxies is 20 attempts per IP: under every per-IP threshold above. What catches it is per-account+IP failures, breached-credential matching (reject or force-reset passwords found via a k-anonymity breach API), MFA or device binding on high-value actions, and success-pattern detection: many distinct accounts succeeding from one ASN in a short window.

Atomic sliding window in Redis, so concurrent requests can't both pass:

lua -- KEYS[1]=bucket ARGV: now_ms, window_ms, limit, member local now = tonumber(ARGV[1]) redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - tonumber(ARGV[2])) if redis.call('ZCARD', KEYS[1]) >= tonumber(ARGV[3]) then return 0 end redis.call('ZADD', KEYS[1], now, ARGV[4]) redis.call('PEXPIRE', KEYS[1], ARGV[2]) return 1

Failure modes I'd watch: lockout-as-DoS (alert on lockout spikes across many accounts from few IPs); CGNAT false positives (track challenge rate by ASN, keep per-IP limits loose); Redis down (fail open with an in-process limiter and a loud alert. Failing closed on login is a self-inflicted outage); and enumeration through the reset and registration flows, which are usually forgotten.

Detection: distinct accounts per IP/ASN, failure-to-success ratio per account, CAPTCHA solve rate, step-up completion rate. A rising distinct-accounts-per-IP p99 is the earliest stuffing signal.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How do you prevent account recovery from becoming the weakest authentication path?

Answer

First 90 seconds. Assume the attacker already holds the user's email and phone number: recovery is where that assumption gets tested. Treat recovery as a first-class authentication path: it must demand evidence at least as strong as primary login, it must be delayed and announced, and any one-time secret must be consumed atomically. Concretely: pre-generated recovery codes or a bound trusted device as the fallback, a hold window before the reset takes effect, notification to a channel the attacker does not control, and a single-use token invalidated in the same transaction that validates it.

Why recovery is the weak path. If primary login is WebAuthn or TOTP and recovery falls back to SMS, the account's real strength is SMS. A SIM swap moves the number to an attacker's SIM in minutes to hours, usually via a bribed or social-engineered carrier rep, and the recovery SMS lands on the attacker's phone. TOTP is not exposed to that: the secret lives on the device, and a code is dead after its 30-second step. NIST SP 800-63B-3 classifies SMS and voice as restricted out-of-band authenticators: acceptable at AAL1, not at AAL2/AAL3.

Pick the fallback deliberately.

FallbackAttacker mustBreaks whenFits
Recovery codes (10–16, hashed)steal a file or a printed sheetuser loses them and reissue is weakhigh-value, technical users
Trusted device (bound key)steal that devicedevice lost with the primaryconsumer with a second device
Trusted contacts (k-of-n)compromise k contactscollusion; coordination stallsnon-technical consumer
SMS / voiceSIM swapcarrier portlegacy only
Delay + notification onlywait out the hold and suppress the alertuser never noticeslow-value consumer

Consume one-time secrets atomically. A recovery code checked and then marked used in two statements is a race: two concurrent requests both read used_at IS NULL. One statement closes it.

SQL
-- Postgres 16, default READ COMMITTED
UPDATE recovery_code
   SET used_at = now()
 WHERE user_id   = $1
   AND code_hash = $2
   AND used_at IS NULL
RETURNING id;

Trace two concurrent requests carrying the same code: the first UPDATE takes the row lock and sets used_at. The second blocks on that lock; when the first commits, Postgres re-evaluates the WHERE clause against the new row version, used_at IS NULL is now false, and it matches zero rows. Exactly one caller gets an id back: treat zero rows as a failed recovery. Store code_hash as Argon2id (OWASP baseline: m=19 MiB, t=2, p=1), never the code itself.

A hold window, traced. Attacker holds the mailbox, not the phone (addresses hypothetical):

tNo hold24 h hold + push to phone
0POST /recoverPOST /recover
0link livelink issued, inert
+1 minattacker sets password, session issuedattacker cannot use the link
+2 min—push: "reset requested from 203.0.113.7"
+10 min—user taps "not me"; request cancelled, link dead
+24 h—link expires unused

The hold only works with notification to a channel the attacker lacks. If the attacker also has the phone, the push goes to them, which is why the fallback is a recovery code or a bound device, not another SMS.

Guessing arithmetic. A 10^6 code space with 100 attempts/hour gives 100/10^6 = 0.01% per hour. Capping at 5 attempts/hour per account drops it to 0.0005%. NIST SP 800-63B-3 allows up to 100 consecutive failures; 5/hour with human review after is a defensible tightening.

Failure modes and detection. SIM swap: detect via carrier port notifications and a sudden device/geo change at next login. Mailbox compromise: detect via impossible travel on the mail account and a reset requested from a new ASN. Code replay: detect by alerting on any code row matched twice, which the constraint above makes impossible. Account enumeration: detect via per-IP and per-account rate limits on the recovery endpoint and uniform responses.

When not to use it. A 24-hour hold is wrong for production break-glass access, where the on-call engineer needs in now; use a hardware key plus a sealed break-glass credential instead. Recovery codes are wrong for a user base that will lose them and has no secure reissue path: there, k-of-n trusted contacts with a short hold beats a code nobody can find.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you prevent cross-site request forgery in both cookie-based and token-based web applications, including SameSite behavior, token binding, and why CORS alone is not a defense?

Answer

CSRF exists because the browser attaches ambient credentials (cookies, HTTP Basic, TLS client certs) to any request to your origin, no matter which site caused it. So I'd establish the premise first: if the app sends Authorization: Bearer from JS memory, there is no ambient credential and classic CSRF does not apply. The moment that token lives in a cookie, it is a cookie-based app again and every cookie defense applies.

For cookie-based apps I layer three controls, because each has a hole.

1. SameSite. Lax is the browser default now (Chrome 80+, Firefox, Safari). It blocks cross-site POST/PUT/DELETE and cross-site fetch, but still sends the cookie on top-level GET navigation, so no state-changing GETs, ever. Chrome also has a Lax+POST grace: cookies set less than 2 minutes ago are sent on a cross-site top-level POST, which is exactly the window a login-CSRF or freshly-set-session attack lands in. Strict breaks the OAuth redirect back into your app and links from email; use Lax plus tokens instead.

2. A synchronizer token bound to the session. 256 bits of randomness, HMAC'd together with the session ID so a token lifted from one session cannot be replayed in another, delivered in a hidden field or an X-CSRF-Token header, compared in constant time. Unsigned double-submit cookies are the weak version: anyone who can set a cookie on a subdomain, or who wins a subdomain takeover, plants a matching cookie and header. Signing with a server key bound to the session closes that.

3. Origin / Sec-Fetch-Site checks as defense in depth. Reject state-changing requests whose Origin is not yours; Sec-Fetch-Site: same-origin is set by the browser and page JS cannot forge it.

CORS is not a defense here, and this is the part interviewers probe. CORS controls whether JS may read a response. A cross-site HTML form POST is a "simple request" (no preflight, no custom headers) so it is sent and the side effect happens even though the attacker never sees the reply. Preflight only fires for non-simple requests. Worse, reflecting the request Origin into Access-Control-Allow-Origin alongside Allow-Credentials: true turns CORS into the vulnerability rather than the mitigation.

For token-based SPAs: keep the access token in memory, the refresh token in a SameSite=Strict, HttpOnly, __Host- prefixed cookie with rotation, and send the access token as a header. That removes ambient auth from the request path entirely.

js // Node 20, Express 4.19: signed double-submit bound to the session import crypto from 'node:crypto';

const KEY = process.env.CSRF_KEY; // 32 random bytes, per environment

function issue(sessionId) { const nonce = crypto.randomBytes(32).toString('base64url'); const mac = crypto.createHmac('sha256', KEY) .update(${sessionId}.${nonce}).digest('base64url'); return ${nonce}.${mac}; // set as __Host-csrf cookie AND returned to the page }

function verify(req) { const cookie = req.cookies['__Host-csrf'] ?? ''; const header = req.get('x-csrf-token') ?? ''; const [nonce, mac] = cookie.split('.'); if (!nonce || !mac || header !== cookie) return false; const expected = crypto.createHmac('sha256', KEY) .update(${req.session.id}.${nonce}).digest('base64url'); return crypto.timingSafeEqual(Buffer.from(mac), Buffer.from(expected)); }

ControlBlocksDoes not block
SameSite=Laxcross-site POST/PUT/DELETE, cross-site fetchtop-level GET navigation; Chrome's 2-minute Lax+POST grace
SameSite=Strictevery cross-site send, including top-level GETbreaks OAuth return redirects and email links
Session-bound synchronizer tokenall state-changing requestsXSS (the token is readable)
Signed double-submitsubdomain cookie injectionXSS
Origin / Sec-Fetch-Site checkmost cross-site requestsclients that strip Origin
CORSJS reading the responsethe request itself: simple requests still execute

Failure modes I'd watch: XSS defeats every CSRF control, since the token is readable; a JSON API that also accepts text/plain or form-encoded bodies is reachable by a simple request, so enforce application/json and reject other content types; login CSRF (attacker logs you into their account) needs the same token on the login form; and SameSite=None for embedded or partner flows reopens everything, so those endpoints need tokens. Detection: log and alert on Origin/Sec-Fetch-Site mismatches and CSRF verification failures per session. A spike is either a broken deploy or an active campaign.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do you secure business logic against replay, races, and workflow bypass?

Answer

Assumptions: multi-tenant HTTP API, Postgres 16, an async queue for slow steps, clients that retry on timeout.

Core answer (first 90 seconds). Three invariants, all enforced server-side. The UI sequence is not a control.

  1. Every state change is a guarded transition. The row stores its state and a version. The update names the state it expects to leave and the version it expects to see. Zero rows affected means someone else already moved it: reject, don't silently retry.
  2. Every mutating request carries an idempotency key binding caller, operation and a hash of the payload. The key is written under a unique constraint before any work starts, so a replay collides instead of re-executing.
  3. Every approval is a signed, expiring challenge covering a hash of the transaction data. Change the amount and the signature no longer covers what you are about to do.

Mechanism.

Idempotency, Postgres 16:

SQL
INSERT INTO idempotency (key, caller_id, payload_hash, status)
VALUES ($1, $2, $3, 'in_progress')
ON CONFLICT (key) DO NOTHING;

Trace, two requests with the same key 50 ms apart:

  • A inserts 1 row, does the work, updates the row to done with the stored response.
  • B inserts 0 rows. It reads the row: in_progress → return 409 with Retry-After; done → return the stored response; caller_id or payload_hash differs → 409, never the stored response.

TTL: Stripe documents 24-hour retention for idempotency keys; set yours to at least your client's maximum retry window, or a late retry re-executes.

Balance race: one statement, no read-then-write:

SQL
UPDATE accounts SET balance = balance - 100
 WHERE id = $1 AND balance >= 100;

Under READ COMMITTED, Postgres re-evaluates the WHERE against the row version it actually locks, so a concurrent debit cannot drive the balance negative; rowcount 0 means insufficient funds. If the invariant spans rows (ledger sum equals balance), use SERIALIZABLE and handle SQLSTATE 40001 with bounded retries: Postgres SSI aborts rather than blocks, and abort rate rises with contention on the same rows.

Challenge: sign {txn_id, amount, payee, nonce, exp} with the server key, exp 5 minutes out, nonce single-use in a TTL store. TOTP-style codes follow RFC 6238's 30-second step; don't reuse that window as your approval lifetime.

Failure modes and how you see them.

FailureDetectionOperational cost
Replay of a captured requestKey collision with mismatched payload hash → 409; alert on the counterOne row per request, 24 h TTL
Double-spend raceReconciliation job compares ledger sum to balance; alert on any driftConditional update serializes on the row; hot accounts need per-account queueing
Workflow bypass (step 3 without step 2)Rejected-transition metric, nonzero from one callerOne indexed lookup
Stale approval after amount changeChallenge hash mismatch → 422User re-approves

Trade-offs. For queued work you have two options: reauthorize at execution, or carry a bounded grant. Reauthorize when the action has external side effects and is not idempotent (charging a card, sending mail): consent is re-checked against current state. Use a grant when the user is gone by the time the job runs: single-use token, TTL around 60 s, bound to the payload hash. A grant measured in hours is wrong: you cannot revoke it, and it outlives the consent it encodes. Reauthorizing everything is also wrong when the queue delay exceeds the session; there is no one to ask.

What would change this: if the downstream system cannot take an idempotency key, you need an outbox with a dedupe table on your side; if the invariant spans services, move it behind one owner rather than coordinating locks.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Threat-model a user-upload feature from request through later download.

Answer

Assumptions. Multi-tenant SaaS; authenticated users upload documents and images (≤25 MB, ≤10 per request) that other users in the same tenant later download in a browser; S3-compatible object store; processing workers run in the same cloud account.

The answer in 90 seconds. There are four trust boundaries (ingress, validation, storage/processing, delivery) and one decision dominates the rest: treat every uploaded byte as hostile until it has been re-encoded, and never serve user content from the application's origin. Everything else is defence in depth around those two.

Ingress. Authenticate and authorize before reading the body, and enforce size at the edge (client_max_body_size 25m in nginx) so a 10 GB chunked upload never reaches the app. Reject a Content-Length that disagrees with the streamed byte count. Rate-limit per user and per tenant.

Validation. Extension and the client's Content-Type are attacker-controlled, so check magic bytes with libmagic and compare against the declared type. A file that is both a valid GIF and a valid JAR (GIFAR) passes any single check; the fix is not to detect polyglots but to re-encode images (decode → re-encode to PNG/JPEG) so the output is a new file containing no attacker bytes. For archives, cap the compression ratio, total uncompressed size and nesting depth.

Storage. The object key is a server-generated UUID, never the user's filename: that kills path traversal and overwrite. The bucket is private, has no public ACL and no execute permission. Tenant ID is part of the key prefix and is re-checked on every read.

Processing. Scanners (ClamAV) and re-encoders run in workers with no network egress, a read-only rootfs, seccomp, a wall-clock timeout and a memory cap. Untrusted status is a column in the database, not an assumption.

Delivery. This is where stored XSS lives. Serve from a separate origin that carries no cookies, and set the headers below.

HTTP/2 200
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="report.pdf"
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'; sandbox
Cross-Origin-Resource-Policy: same-origin

Why it works: attachment stops inline rendering; nosniff stops the browser re-interpreting a .txt as HTML; the separate origin means that even if something does render, it has no session cookie and no same-origin access to the app. Reauthorize the object on every download: a signed URL with a 5-minute TTL, not a permanent public link.

Arithmetic: 42.zip is 42 KB and expands to 4.5 PB. A 1 MB zip at 1000:1 is 1 GB. Cap ratio at 100:1, total uncompressed at 500 MB, depth at 2. A 65535×65535 PNG is 4.29 G pixels ≈ 17 GB decoded RGBA: check dimensions before decode and cap at 100 MP.

Trade-offs. Block vs quarantine vs strip. Blocking on any AV hit produces false positives that lose real documents; quarantine with an appeal path is right for user-facing files. CDR (re-encode) is strongest for images but destroys metadata and breaks some formats. A permissive policy is right only for a single-tenant internal tool where uploaders are trusted and files never leave the tenant.

Failure modes. AV timeout leaves a file stuck in pending: detect with a queue-age alert. Re-encoder OOM causes a worker crash loop: detect with restart count. Open redirect via ?next= on the download endpoint; SSRF if the app fetches a user-supplied URL to import: allowlist schemes and block link-local (169.254.169.254).

What would change the decision. If files are never rendered in a browser (API-only consumers), the separate-origin and CSP work drops. If uploads are internal-only, CDR cost may not be worth it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you safely consume signed updates or serialized data from another system?

Answer

Assumptions: the producer is a separate team or vendor; payloads arrive over TLS but may be queued, persisted, or relayed, so the channel alone can't be trusted; I control the consumer and its key store. Format is JSON or Protobuf.

Core answer (first 90 seconds). Verify the signature over the exact received bytes before parsing, using a pinned key set I control: never a key the message names. Then parse with a data-only parser under hard size and depth caps. Then apply the checks a signature can't give you: audience, expiry, and a monotonic version to stop replay. A valid signature proves who sent it and that it wasn't altered; it proves nothing about whether the content is safe or current. So authorization, semantic validation, and sandboxing still apply.

Why verify first. Parsing untrusted bytes is where the exploitable bugs live: parser differentials, decompression bombs, object-construction gadgets. If you parse to read a key id, you've already run the risky code. Keep the key id in a signed header outside the body, or try the small pinned set directly.

Python
# Python 3.12, cryptography 42.x
import json
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.exceptions import InvalidSignature

MAX_BYTES, MAX_DEPTH = 1 << 20, 32   # 1 MiB, 32 levels

def _reject_constant(name):          # NaN / Infinity are not valid JSON
    raise ValueError(f"non-finite: {name}")

def _depth(obj, d=0):
    if d > MAX_DEPTH:
        raise ValueError("too deep")
    if isinstance(obj, dict):
        for v in obj.values(): _depth(v, d + 1)
    elif isinstance(obj, list):
        for v in obj: _depth(v, d + 1)

def _try(k, sig, raw):
    try:
        k.verify(sig, raw); return True
    except InvalidSignature:
        return False

def consume(raw: bytes, sig: bytes, pinned: list[Ed25519PublicKey]) -> dict:
    if len(raw) > MAX_BYTES:
        raise ValueError("oversize")
    if not any(_try(k, sig, raw) for k in pinned):   # verify BEFORE parse
        raise ValueError("bad signature")
    doc = json.loads(raw, parse_constant=_reject_constant)
    _depth(doc)
    return doc

Trace: replay. Producer signs config v41 at 10:00. An attacker replays the identical bytes at 10:05. The signature verifies: bytes unchanged, key still pinned. The version check sees last_seen == 41, incoming 41, and rejects. Detection is a counter on non-monotonic versions with an alert. Skip it and a revoked feature flag gets switched back on: that's the blast radius.

Trade-offs.

choiceuse whencost
mTLS onlylive connection, never persisted, same trust domainno protection once bytes are stored or relayed
detached signature (Ed25519)payload crosses queues, disks, third partieskey distribution and rotation
schema registrymany producers, central compatibility enforcementruntime dependency; registry outage blocks ingest
embedded version + local schemafew producers, low volumeyou enforce compatibility yourself

Failure modes, with detection.

  • Compromised producer key: signature valid, content hostile. Detect via semantic anomaly and allowlist; bound the blast radius by sandboxing the consumer (no shell, no native object construction).
  • Parser differential: JSON duplicate keys or Protobuf unknown fields read differently by two consumers. Detect by canonicalizing and rejecting duplicates; otherwise two systems act on different values from identical bytes.
  • Resource exhaustion: a 10 MB nested array OOMs the consumer without the 1 MiB / 32-depth caps.
  • Key rotation: pin old and new during an overlap window; watch the verification-failure rate; rotate without overlap and every update is rejected.

Budget. Ed25519 verify is roughly 50 µs, about 20k/s per core. At 10k msg/s you spend ~1 core just verifying, so size the consumer for it.

What would change my decision: if the payload never leaves a live mutually-authenticated connection and is never persisted, mTLS alone is enough and the signing layer is overhead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design a secure software supply-chain program for a web service.

Answer

Scope: Kubernetes service, CI on GitHub Actions, images in GHCR, deploys via Argo CD. Four gates, each with one enforcement point: dependencies resolve through a proxy, builds run on a hosted runner with OIDC and non-falsifiable provenance, images are signed keylessly, and admission verifies signature plus provenance. The program is only as strong as the last gate that can say no.

Dependencies. Commit lockfiles (package-lock.json, go.sum) and run npm ci, not npm install, so the lockfile is authoritative. Route all resolution through an Artifactory/Nexus virtual repo whose upstream is npmjs, with @myorg/* scoped to the local repo only: that scope routing is what stops dependency confusion, because an attacker's public @myorg/utils is never reachable. Emit an SBOM at build (syft ghcr.io/myorg/api@sha256:... -o cyclonedx-json) and attach it as an attestation. Gate: block on CVSS >= 9.0 with a fix available and reachable code; waivers expire in 30 days.

Build integrity. GitHub Actions OIDC assumes an AWS role via assume-role-with-web-identity, 1-hour session, trust policy scoped to repo:myorg/myrepo:ref:refs/heads/main. No long-lived secrets; fork PRs get neither secrets nor an id-token. Use the slsa-github-generator reusable workflow: it signs provenance with a key held by Fulcio, not by your repo, which is what makes it non-falsifiable.

SLSA v1.0 Build levelRequiresWhat it buys
L1Provenance exists, generated by the buildYou can see what was built
L2Hosted build platform, signed provenanceTamper-evident provenance
L3Hardened platform, isolated builds, non-falsifiable provenanceThe build cannot forge its own provenance

SLSA v1.0's Build track stops at L3; the "L4" from the v0.1 draft no longer exists. L2 is a reasonable start; L3 is the target for anything internet-facing.

Signing and admission. cosign sign keyless: Fulcio issues a ~10-minute certificate bound to the workflow identity, and the signature lands in Rekor. Verify with:

cosign verify \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  --certificate-identity-regexp '^https://github.com/myorg/myrepo/.github/workflows/release.yml@refs/heads/main$' \
  ghcr.io/myorg/api@sha256:...

Enforce with a cluster-wide Kyverno verifyImages policy (keyless attestor, same subject regexp, plus a slsa attestation predicate), failurePolicy: Fail, no namespace exempt.

Worked trace: malicious dependency. An attacker compromises an npm maintainer and publishes left-pad@1.3.1 with a postinstall that exfiltrates env vars. Renovate opens a lockfile bump. CI runs npm ci on the fork-safe runner: the postinstall executes but finds no secrets and no OIDC token. If it merges anyway, the build is legitimate, provenance is valid, and admission passes: signing proves origin, not safety. Detection is the SBOM: Dependency-Track matches the new version against the advisory, and reachability shows the postinstall is a devDependency absent from the runtime image. Response: revert the lockfile, rebuild, re-sign.

Failure modes. A compromised workflow identity is the residual risk of keyless signing: alert on Rekor entries whose identity is outside the allowlist. Admission fails open if a namespace lacks the policy or the controller is misconfigured; alert on pods whose image digest has no Rekor entry. L2 provenance is signed by the build itself, so a compromised build can lie: that is the concrete reason to pay for L3.

Tradeoffs. Admission verification costs latency: in a 100-pod rollout, roughly 80 ms per pod cold against Rekor and ~5 ms warm with caching (test figure, not a vendor number). Blocking on CVEs slows delivery, hence expiring waivers rather than permanent exceptions.

What changes the decision. Internal, low-risk service: L2 plus scanning is enough. FedRAMP or similar: L3, air-gapped builds, and two-party review on the release workflow.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

A scanner reports 400 CVEs across your dependency tree. Walk me through how you identify, prioritize, and remediate them, and how reachability and exploitability change the order.

Answer

First I'd challenge the number. A scanner's 400 findings are an inventory, not a work queue: most are one CVE counted once per service, or a package that ships but whose vulnerable function is never called. This is the A06:2021 Vulnerable and Outdated Components problem, which the 2025 list folds into A03 Software Supply Chain Failures. Assumptions I'd state up front: every service commits its lockfile, and every built artifact gets an SBOM, so I can map package@version → artifact → running service.

Dedupe and attribute. Collapse by (package, version, advisory ID), then map each to the artifacts that actually contain it. One CVE in a base image shared by 30 services is one platform fix, not 30 tickets. Dev-only and build-only dependencies get a separate track: they still matter when they run with CI credentials, but they aren't production exposure.

Rank on three axes, not CVSS alone.

  • Reachability: does our code actually reach the vulnerable symbol? govulncheck does this for Go with a call graph; Java and JS need an SCA tool that does the same, or manual tracing. Reflection, dynamic dispatch, plugin loading and deserialization defeat static reachability, so for those treat "not reachable" as a hypothesis, not a fact.
  • Exploitability: EPSS probability plus CISA KEV membership. KEV means observed exploitation; EPSS is a probability, not a verdict.
  • Exposure and blast radius: is the vulnerable path reachable from untrusted input, and what can the component do: deserialize, spawn a process, read the filesystem, hold a session?

That gives tiers with SLAs:

tiercriteriaSLA
P0KEV-listed, reachable, internet-exposed, RCE or auth bypass24–72 h, patch or mitigate
P1reachable and exposed, EPSS > 0.1 or CVSS ≥ 97 days
P2reachable, not exposed, no public exploit30 days
P3not reachable, dev-only, build-onlynext scheduled upgrade, ≤ 90 days
P4no fix publishedcompensating control, re-check monthly

Remediate at the right layer. Prefer a direct bump of the top-level dependency; when the vulnerable version is pinned by a transitive parent, use a resolution override and re-run the suite:

json // package.json, npm 10 "overrides": { "minimist@<1.2.6": "1.2.6" }

Then confirm what actually resolved, npm ls minimist, because an override that silently doesn't apply is worse than no override. For base-image CVEs, rebuild the image rather than patching inside a running container. When no fix exists, the compensating control has to be specific: disable the feature, block the vulnerable route at the gateway, or constrain the component's network and filesystem reach.

Reachability output is what makes the triage defensible. Illustrative govulncheck shape:

Found 2 vulnerabilities in packages you import and 3 in modules you require, but your code doesn't call the vulnerable symbols. Vulnerability #1: GO-2024-XXXX Module: golang.org/x/net Found in: golang.org/x/net@v0.23.0 Fixed in: golang.org/x/net@v0.24.0 Example traces found: #1: internal/proxy/handler.go:88:23: proxy.Handler.ServeHTTP calls http2.Transport.RoundTrip

Failure modes I'd watch: scanner noise drowning the P0s; version-match false positives when the build doesn't use the lockfile; reachability false negatives through reflection; and a mass upgrade that breaks production because nobody ran the integration suite. Detection is the SLA itself: track open findings per tier, count KEV-listed reachable findings past SLA, and re-scan on every build, failing the build only for P0/P1.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Secure a CI/CD pipeline against software and data integrity failures.

Answer

Assumptions first. The threat model is the pipeline, not the app: an attacker who can change source, a build input, a runner, or a deploy credential. Runtime security is a separate question.

Core answer. Every artifact that reaches production must be traceable to a reviewed source revision, built by an identity you can name, and deployed only if that chain verifies at admission. Four properties carry it: provenance, immutability, short-lived scoped identity, and verification at the point of deployment. Anything that doesn't feed one of those four is decoration.

Why each control exists.

Ephemeral runners matter because a persistent runner is somewhere to leave a modified compiler, a poisoned cache, or a shell profile that rewrites the artifact after the build step. A fresh VM per job removes the persistence. The cost is cold caches, so you keep a content-addressed cache keyed by the lockfile hash and verify it on restore instead of trusting it.

Short-lived credentials matter because a leaked long-lived registry or cloud key is usable from anywhere, forever. GitHub Actions OIDC with id-token: write lets the job exchange a workflow-bound token for cloud credentials scoped to that one job; the token dies with the job. Fork PRs get no secrets at all: pull_request, never pull_request_target with a checkout of the fork head.

Signing in a protected step matters because if arbitrary job code can invoke the signer, the signature attests to nothing. Keyless signing binds the signature to the workflow identity: Fulcio issues a certificate valid about 10 minutes whose SAN is the workflow ref, and Rekor records it publicly. That is what makes SLSA v1.0 build L3's non-forgeable provenance mean anything.

Anti-rollback matters because a validly signed old image is still a validly signed old image. Without a version check at admission, anyone with deploy rights just redeploys the release with the CVE.

FailureControlDetection
Tag overwritten after reviewDeploy by digest; registry tag immutabilityAdmission rejects tag-only refs; deployed digest ≠ provenance digest
Poisoned dependency or actionLockfile hashes; actions pinned to full commit SHASBOM diff vs previous build shows an unexpected package
Runner persistence between jobsEphemeral runner per jobProvenance builder ID changes; files no step created
Leaked long-lived deploy keyOIDC → job-scoped cloud credsAudit log shows assume-role from an unexpected workflow ref
Attacker signs with your identityKeyless signing bound to workflow ref; RekorRekor entry for your identity you didn't produce
Rollback to a signed-but-vulnerable imageVersion monotonicity at admissionAdmission denies version ≤ deployed
YAML
permissions:
  id-token: write   # job can mint a GitHub OIDC token
  contents: read
jobs:
  build:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@<full-commit-sha>   # v4.2.2, pinned by SHA not tag
      - run: cosign sign --yes ghcr.io/acme/api@sha256:<digest>

Trace at admission (Kyverno verifyImages, Sigstore policy-controller, or Gatekeeper + cosign):

  1. Pod references ghcr.io/acme/api@sha256:abc…; a tag-only ref is denied by policy.
  2. Controller fetches the signature, cosign stores it as tag sha256-abc….sig, and the Rekor entry.
  3. Verifies the Fulcio cert chains to the Sigstore root and its SAN is exactly https://github.com/acme/api/.github/workflows/release.yml@refs/heads/main, issuer https://token.actions.githubusercontent.com.
  4. Verifies the in-toto provenance attestation: builder ID, source repo, commit SHA.
  5. Checks the version label exceeds what is deployed.
  6. Admit. Any step failing denies, and the pod never schedules.

Trade-offs. Keyless removes key theft but adds a hard dependency on Fulcio and Rekor at sign time; air-gapped shops run private Sigstore or KMS-backed keys instead. Strict admission blocks a bad deploy but also blocks you at 3 a.m., so run audit-only in staging first and make break-glass require a second approver plus an audit event. If you don't control the build platform, a third-party SaaS builder, you cannot reach L3; you can only verify what they hand you.

Failure modes to name. A compromised runner shows up as a provenance builder ID you don't recognise. A stolen signing identity shows up as a Rekor entry you didn't produce. A dependency-confusion package shows up as an SBOM delta. All three are detected by comparing against the previous build, not by reading logs after an incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design application security logging that is useful and privacy-conscious.

Answer

Core answer (first 90 seconds)

Before I pick a schema I pin three things: what we're detecting (account takeover, privilege abuse, data exfiltration), what we're legally obliged to keep and for how long, and who reads the logs. A SOC analyst, an incident responder, or a customer exercising a GDPR access request. Those three decide the fields. Everything else follows.

Then the design: emit one structured JSON event per security-relevant decision, at the point of enforcement, not reconstructed later from app logs. Log every deny, every privileged action, and every authentication lifecycle event unconditionally. Sample routine allows. Keep PII out at write time rather than scrubbing at read time, because the raw copy is the one that leaks.

The two fields people get wrong are actor and subject. actor is the authenticated principal making the call; subject is the account or resource being acted on. They diverge under support impersonation, delegation, and service-to-service calls. Log only one and you either misattribute the action to the wrong human or you can't answer "what happened to this customer's account", which is the question that actually gets asked during an incident.

JSON
{"ts":"2025-03-11T14:02:07.481Z","seq":88140231,
 "event":"authz.decision","outcome":"deny","reason":"policy_mismatch",
 "actor":"user:8812","subject":"acct:4471","tenant":"t-19",
 "action":"invoice.read","resource":"inv:9f3c","session":"a41c9e02d7b6f318",
 "policy":"rbac-2025.03.04","trace_id":"4f2a","src_ip":"203.0.113.7"}

session is the first 16 hex chars of SHA-256 over the session ID: enough to correlate a chain, useless for replay. seq is a per-host monotonic counter, because wall clock alone reorders under an NTP step. resource is an opaque ID, never the raw path or query string.

The trade-off, with numbers

A service at 500 rps emits 43.2M authz decisions a day. At ~500 bytes each that's 21.6 GB/day, 2.6 TB over 120 days.

ChoiceDetection valueCost
Log every decisionComplete allow/deny trail21.6 GB/day, 2.6 TB/120d
Deny always, allow 1/1000Catches every block; may miss the one allow that matters~130k events/day, 65 MB/day, 7.8 GB/120d
Raw IP + user agent, 12 monthsGeo/device anomaly detectionPII store; conflicts with GDPR Art. 5(1)(e)
IP truncated to /24 after 30 daysStill flags new-network loginsLoses host attribution after 30 days

I'd take the middle row plus an exception: always log allows for privileged actions and for a first-seen (actor, resource) pair. That's where the sampled-allow blind spot actually bites.

Failure modes and how you'd see them

Log injection. A username containing a newline forges a second event in any line-oriented format. Detect by schema-validating at ingest and alerting on the reject rate: a spike is itself a signal, though a noisy client can drown it.

Clock skew. Two hosts 4 s apart make a causal chain read backwards. Monitor NTP offset per host, alert above 1 s, and rely on seq for intra-host order.

The log store becomes the breach. It holds PII and authz decisions. Audit reads of the store itself and alert on one principal exporting more than 10k events in 5 minutes. You now need a second pipeline watching the first.

Retention drift. Raw IPs kept "just in case" past their stated purpose. Run a scheduled job reporting the age distribution of each PII field; anything older than its tier is a finding.

DataKeepBound
Auth/authz events, no PII12 months, 3 hotPCI DSS v4.0 10.5.1
Events with IP/UA30 days raw, then truncatedGDPR Art. 5(1)(e)
Tokens, passwords, recovery secretsneverOWASP Logging Cheat Sheet

Finally, prove the queries still work: replay a past incident's events through the query set that found it, quarterly. If that query returns nothing, the schema drifted and the detection is gone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How do you prevent log injection and log forging: including CRLF injection into log lines, attacker-controlled data corrupting log parsers, and forged entries that mislead an investigation?

Answer

Assume a service that logs request context (username, User-Agent, path, form values) and ships it to a SIEM. The rule that does most of the work: untrusted data is never concatenated into a log line; it is passed as a typed field to a serializer that escapes control characters. Everything else is depth.

A log line is a record format with delimiters. If the attacker controls bytes inside it, they control the record boundaries. \r\n ends the line, so whatever follows becomes a new entry, and if the format looks right, the SIEM indexes it as genuine.

Trace: the attacker sets User-Agent to

Mozilla/5.0\r\n2025-06-01T00:00:00Z INFO auth ok user=root src=127.0.0.1

A naive log.info(f"req ua={ua}") writes two lines; the second is a forged successful root login. json.dumps writes one line with \r\n escaped as \\r\\n, and the field stays opaque.

python

Python 3.12

bad: attacker controls record boundaries

log.info(f"login user={username} src={ip}")

good: typed field, serializer escapes

log.info("login", extra={"user": username, "src": ip, "outcome": "ok"})

json.dumps(...) -> {"event":"login","user":"admin\r\n...","src":"..."}

Encoding depends on the sink, and each sink is a separate injection surface:

sinkfailurecontrol
text file / syslogCRLF splits recordsescape \r \n \t and other C0 controls in untrusted fields
JSONsafe only with a real serializernever build JSON with f-strings
terminal (tail)ANSI/CSI escapes rewrite the screen, hide linesstrip 0x1B and CSI sequences
SIEM parserdelimiter collision, field confusiontyped schema; no free-text interpolation
HTML log viewerstored XSScontext-encode at render

Trade-off: percent- or base64-encoding untrusted fields is lossless and unambiguous but makes grep and SIEM search harder. Escaping control characters keeps fields readable and is usually enough: provided every consumer treats the field as opaque and does not decode it again.

Two things people miss. First, log content must never be interpreted: Log4Shell (CVE-2021-44228) executed code from ${jndi:ldap://...} inside a logged header in Log4j 2 before 2.15.0. Message lookups off, and no template evaluation of logged values. Second, truncation and double decoding: capping a field at 1 KB can cut an escape sequence in half, and a shipper that decodes once plus a viewer that decodes again re-creates the newline.

Forged entries that arrive through the normal path cannot be told apart by content. You need provenance: append-only storage, per-host sequence numbers, authenticated TLS shipping, clock sync, and a hash chain over entries so a gap or an edit is detectable. Alert on control characters in fields that should never contain them, on sequence gaps, and on log-volume anomalies.

Failure modes worth naming: multi-line stack traces are legitimate, so a parser cannot simply reject newlines. It must distinguish trusted multi-line output from untrusted fields. Unicode line separators U+2028/U+2029 and homoglyph usernames forge "admin" with no CRLF at all. And a log viewer that renders raw fields turns a logging bug into stored XSS.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How do you triage and prioritize a newly reported vulnerability?

Answer

What I'd say in the first 90 seconds

Triage answers one question: what do we do in the next 24 hours, and who owns it. Not "how bad is this CVE."

Three assumptions I'd state before scoring anything: an asset inventory that maps hosts to owning teams, an intake channel that timestamps every report, and a written SLA policy that ties a severity tier to a remediation deadline. Without those, triage becomes an argument about a number.

Then I answer reachability first. A CVSS 9.8 in an internal service with no route from the internet and no authenticated path is a 30-day ticket. A CVSS 7.5 on an internet-facing edge is a today ticket. Exposure and reachability dominate the base score, which is why I never prioritize on CVSS alone.

The three signals

  • CVSS v3.1 base: intrinsic, environment-independent severity. CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H scores 9.8.
  • EPSS: probability, 0 to 1, that a CVE is exploited in the wild in the next 30 days. It's a population-level model, not a claim about our asset.
  • CISA KEV: confirmed exploitation. If a CVE is in KEV, EPSS stops mattering; it's already happening. KEV is a floor, not a ceiling: it lags exploitation, so absence from KEV is not evidence of safety.
CVECVSS baseEPSSKEVReachableTierDeadline
A9.80.94yesinternet-facingCritical24 h
B9.80.02nointernal, auth requiredHigh7 d
C7.50.61nointernet-facingHigh7 d
D7.80.01nolocal only, no routeMedium30 d

EPSS values and the deadline column are illustrative of a typical policy. The point is the ordering: CVE-A and CVE-B share a 9.8 base, but EPSS differs by roughly 47× and only one is reachable, so the tier flips from Critical to High.

Choosing an action

Contain, fix, mitigate, accept, or investigate: the criteria matter more than the list.

  • Contain when the fix needs a release cycle and exposure is live: a WAF rule, a network ACL, a feature flag off.
  • Fix when a patch exists and the asset is reachable.
  • Accept only with a named owner, a review date, and a compensating control.
  • Investigate when the report is credible but unreproduced.

Containment is the wrong call when it masks the root cause or breaks a revenue path: blocking an endpoint a payment flow depends on trades a theoretical exploit for a real outage. And "accept" without a review date is just forgetting with paperwork.

Failure modes I've actually seen

  • Inventory gap. The report names a hostname nobody owns; the ticket ages in the queue. Detect it by alerting on unassigned tickets older than 48 hours.
  • Duplicate flood. One CVE across 400 hosts becomes 400 tickets. Dedupe by CVE plus asset group before it reaches a human.
  • EPSS misuse. Treating 0.94 as "we will be breached" and 0.01 as "ignore." It's a 30-day probability across the population, not a per-asset verdict.
  • Containment drift. The WAF rule stays after the patch lands and silently blocks legitimate traffic. Detect it by flagging rules older than 90 days and watching the endpoint's error-rate delta.
  • Priority rot. A ticket scored Medium in January is still Medium in June after the asset became internet-facing. Re-score on exposure change, not on a calendar.

The trade-off in one line

Every hour spent triaging is an hour not spent fixing, so the goal is a defensible decision fast (severity, exposure, exploitability, owner, deadline) and a re-score when any of those four move.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Build a modern application-security verification program around the Top 10.

Answer

What I'd say in the first two minutes

Clarify first: how many services, what CI, what's already running, and what the risk appetite is. Assume ~50 services, polyglot, GitHub Actions, Kubernetes, one platform team, two AppSec engineers.

The program is a mapping, not a tool list. Each OWASP Top 10 (2021) category gets the cheapest evidence that actually catches it, a gate policy per service tier, and a loop that retires controls that stop working.

The mapping is the core answer

Top 10 (2021)Primary evidenceWhy this and not something else
A01 Broken access controlTwo-role integration tests + authenticated DASTSAST cannot see whether this user should reach that object
A02 Cryptographic failuresSecret scanning (Gitleaks) + TLS/config policy testsCatches keys in history and weak protocol settings, not crypto logic
A03 InjectionSAST (Semgrep, CodeQL) + fuzzing on parsersFuzzing finds the parser edge cases rules miss
A04 Insecure designThreat model + ASVS L2 requirements in design reviewNo scanner detects a missing rate limit
A05 MisconfigurationIaC scan (Checkov, tfsec), kube-bench, CIS benchmarksConfig lives in the repo, so scan it there
A06 Vulnerable componentsSCA (Dependabot, Renovate) + CycloneDX SBOM, EPSS triageSBOM answers "are we affected?" in minutes
A07 Auth failuresASVS auth tests + MFA config assertionsAuth bugs are logic bugs; test the flows
A08 Integrity failurescosign signing + SLSA build provenanceProves the artifact came from your pipeline
A09 Logging/monitoringDetection-as-code tests, alert coverage checksA control you can't see fire is untested
A10 SSRFEgress allowlist config tests + DASTThe allowlist is the control; test it directly

Gate, detect, or audit

Deciding criteria: false-positive rate, blast radius, determinism, runtime. Block only where the signal is deterministic and cheap: secret scanning, IaC policy, SBOM presence, signature verification. High-confidence SAST rules block on merge, advisory on PR. DAST takes minutes to hours per target, so it runs nightly, not per-PR. Pen tests are point-in-time and cannot gate a deploy; they set the baseline and feed regression tests.

Failure modes and how you see them

  • Alert fatigue. Below roughly 10% true-positive rate, engineers rubber-stamp. Detect it by median time-to-dismiss: under 30 seconds means nobody read the finding. Cost is real findings buried under noise.
  • Stale exceptions. Every exception carries owner, compensating control and expiry. A weekly job fails the owning repo's build once expiry passes. Miss it and a tier-1 service carries an unowned risk.
  • Coverage drift. A new service ships without the workflow. Diff service inventory (Backstage, k8s) against repos containing the security workflow; alert on the delta.
  • Gate bypass. Admin merges and [skip ci]. Query the audit log for branch-protection bypasses weekly.

Arithmetic that sizes the team

Illustrative: 50 services × 3 scans/day × 20 raw findings = 3,000/week. At 10% true positive that is 300 real findings. Two engineers at 20 triaged findings/day is 15 working days of backlog, which is why tuning rules and raising the gate threshold matters more than adding scanners.

Feedback loop

Every incident or near miss produces a regression test or a new rule, and the standard it violated gets updated. That is the only part that makes the program compound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How do you verify and close a security remediation?

Answer

The 90-second version. Verification and closure are separate gates. Verification asks: is the vulnerability gone everywhere it was reachable? Closure asks: is the fixed artifact the one running in production, and who owns what's left? I keep the ticket open until both have evidence attached. My assumption walking in is that the finding has a reproducer and a named root cause: without a reproducer you can only assert a fix, not verify one, so that's the first thing I establish.

Reproduce, fix, re-run the same reproducer. Take the IDOR case: a tenant-A token fetching GET /api/v1/invoices/9107 returns 200 with tenant B's invoice. The fix adds a tenant predicate to the shared repository method. The gate is that the identical request now returns 404, and the positive control, tenant A fetching its own invoice 8842, still returns 200. A fix that breaks the positive control is a regression, not a remediation.

Enumerate variants before closing. The root cause is a pattern, not a line. I grep for every caller of the patched method and every route that reaches the same table. In this case /api/v1/invoices/{id}/pdf shares the repository call, so it gets the same test. A Semgrep rule pinned to the repository method catches the next endpoint someone adds.

Python
def test_cross_tenant_invoice_is_not_readable(client, tenant_a_token, tenant_b_invoice_id):
    r = client.get(f"/api/v1/invoices/{tenant_b_invoice_id}",
                   headers={"Authorization": f"Bearer {tenant_a_token}"})
    assert r.status_code == 404
    assert str(tenant_b_invoice_id) not in r.text

def test_owner_still_reads_own_invoice(client, tenant_a_token, tenant_a_invoice_id):
    r = client.get(f"/api/v1/invoices/{tenant_a_invoice_id}",
                   headers={"Authorization": f"Bearer {tenant_a_token}"})
    assert r.status_code == 200

Prove the artifact shipped. A merge commit is not a deployment. I compare the running image digest against the digest CI built from the merge SHA: kubectl get deploy invoice-api -o jsonpath='{.spec.template.spec.containers[0].image}' against the registry digest. If they differ, the fix is in git and not in production, and the ticket stays open.

GateEvidenceFails when
ReproducerOriginal request now 404, positive control 200Fix applied to the controller, not the shared service
VariantsSame test on /pdf and every callerNew endpoint added after the grep
ArtifactRunning digest == CI digest for merge SHARollout stalled on a failing readiness probe
ProductionReproducer re-run against the edge, not just originCDN serves the cached 200
ClosureOwner, evidence links, exception expirySuppression with no expiry date

Trade-offs. A full DAST pass against staging takes hours and floods the queue with noise; a targeted retest plus a Semgrep rule over the repo takes minutes. I use the targeted retest as the release gate and schedule the full scan as a backstop, not a blocker. When the fix needs a schema migration that can't ship same-day, the choice is block the release or accept a documented exception with a named owner and a hard expiry: I take the exception only if the exposure is bounded and the expiry is in the record, never as a silent scanner suppression.

Failure modes and how I catch them. Fix in the repo but the deployed image predates the merge: caught by the digest comparison, not by the reproducer, which passes against staging. Suppression with no expiry: caught by a weekly report of suppressions past their date. Cache serving the stale response: caught by re-running the reproducer against the edge. Each of these is cheap to detect and expensive to miss, which is why they're gates rather than checklist items.

Closing. The ticket closes with the reproducer output, the variant results, the digest match, the owner, and any residual risk with an expiry. I track recurrence over 30 and 90 days; a finding that reappears means the root cause was never fixed, only the symptom.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design a secure multi-tenant web platform using all ten OWASP 2025 risk categories.

Answer

Assumptions. Tenants are mutually untrusted organisations sharing one Postgres 16 cluster and one schema; every tenant-scoped row carries tenant_id. EU tenants must keep data in the EU. The service is a Python API behind a gateway. I'm using the OWASP Top 10 2025 release-candidate ordering: it is still an RC, so confirm the final names before quoting them in an interview.

The isolation model, first. Three layers, each independently able to stop a cross-tenant read:

  1. Identity: the IdP issues a token with a tenant_id claim; the gateway rejects any request whose URL tenant does not match the claim.
  2. Data: Postgres row-level security, deny-by-default, tenant set per transaction.
  3. Keys: a per-tenant envelope key in KMS, so a row that escapes is ciphertext under a key the attacker does not hold.
SQL
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON documents
  USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);

The app runs SET LOCAL app.tenant_id = $1 inside each transaction. SET LOCAL dies with the transaction, so a pooled connection cannot carry the previous tenant's context into the next request. If the app forgets to set it, current_setting(..., true) returns NULL, the comparison is NULL, and no rows match: fail-closed.

Trace. Tenant A's user requests /api/documents/<id owned by tenant B>. The gateway passes it (token tenant = URL tenant = A). The query runs with app.tenant_id = A; RLS filters the row; the handler sees zero rows and returns 404, not 403: a 403 would confirm the id exists somewhere else. Detection: a rate alert on 404s against /api/documents/* from a single tenant, not on individual 404s.

The ten categories against this design.

CategoryControlFailure mode → detection
A01 Broken Access ControlRLS + gateway tenant claim + per-object check + egress allowlistA new table ships without RLS → nightly job asserts relrowsecurity on every tenant-scoped table
A02 Security MisconfigurationConfig as code, sslmode=verify-full, no default credentialsA debug flag reaches prod → drift check diffs running config against the signed manifest
A03 Software Supply Chain FailuresPinned digests, SBOM, provenance attestationA transitive dependency is hijacked → build rejects unsigned artefacts
A04 Cryptographic FailuresTLS 1.3, AES-256-GCM per-tenant envelope keys, KMS rotationA key reused across tenants → KMS policy denies cross-tenant decrypt, audit-logged
A05 InjectionParameterised queries only; output encodingA raw f-string query → static analysis catches it; RLS still bounds the blast radius
A06 Insecure DesignThreat model per feature; tenant quotas designed inA feature ships with no tenant boundary → design-review gate
A07 Authentication FailuresOIDC, MFA for admins, short-lived tokensToken replay from two ASNs → alert
A08 Software or Data Integrity FailuresSigned artefacts, signed webhooks, upload checksumsTampered upload → checksum mismatch rejects
A09 Logging & Alerting FailuresStructured logs carrying tenant_id, PII redaction, 404-spike alertsPII in logs → redaction test in CI
A10 Mishandling of Exceptional ConditionsFail-closed defaults, idempotent retries, bounded queuesUnhandled exception returns 200 with an empty body → contract tests

Trade-offs. RLS vs schema-per-tenant vs database-per-tenant. RLS: one migration path, cheap, but one BYPASSRLS role or one missing policy is a cross-tenant breach, and tenants share the connection pool. Schema-per-tenant: better blast radius, per-tenant migrations, painful past a few thousand tenants. Database-per-tenant: strongest, and the only thing that satisfies some regulated contracts, at linear cost. Decide on tenant count × isolation requirement: RLS by default, database-per-tenant for the regulated tier.

Noisy neighbour. A 20-connection pool; one tenant fires 200 concurrent report queries and saturates it: p99 for everyone else goes from 40 ms to 180 ms (hypothetical figures). Fix: a per-tenant connection quota (4 of 20) plus a 5 s statement timeout, so the offender is throttled rather than the pool.

If pushed. The isolation model is the design; the ten categories are the checklist I verify it against, not the design itself.

Curated: · Written: · Reviewed:

Difficulty: Hard