Secure Coding and Application Security Questions
Writing and reviewing code that resists attack. Covers the OWASP Top Ten and common web vulnerabilities (XSS, SQL injection, CSRF), input validation, secure coding practices and security code review, static application security testing (SAST), API and HTTP security, database and frontend security, and mobile app security. The application-layer defense discipline for engineers building software.
How would you detect insecure-deserialization attacks using application instrumentation and runtime telemetry? Describe the specific log events, exception patterns, and profiling metrics you would capture, what sampling strategy you would use to avoid overloading the system, what automated mitigations you might trigger, and suggest both short-term detection heuristics and longer-term developer fixes.
Sample Answer
Direct answer
Detecting insecure-deserialization attacks through instrumentation means watching for the specific, observable byproducts of a gadget chain being probed or fired: type-resolution exceptions that should never happen in normal traffic, filter rejections if a serialization filter is already deployed, and profiling anomalies (unusual stack depth, CPU (Central Processing Unit) or memory spikes during a readObject() call) that a legitimate, well-formed payload of an expected type never produces. Because deserialization is not a naturally high-volume event on most services, a fixed-rate or per-request sampling strategy risks missing the exact anomalous request that matters, so the right approach is to sample everything at low cost (log a lightweight event per call) and only capture expensive detail (full stack traces, payload snapshots) on the anomalous subset, which keeps overhead bounded without blinding the system to the events that count.
Structured elaboration
Specific log events to capture, at every deserialization call site. Structure each event with a fixed schema so it can be correlated across services and aggregated cheaply:
- Call-site identifier (service, code path) and the declared expected type(s) for that site.
- Outcome: success, filter-rejection (if a serialization filter is present), or exception, with the exception's fully-qualified class name.
- The resolved runtime type actually constructed, when resolvable, even on a rejected attempt, since the rejected type name is itself high-value forensic data.
- Caller identity/source (session, API key, source IP), so events can be grouped by originator and repeated attempts from the same source stand out.
- Payload size and, if a serialization filter reports it, object-graph depth and reference count at the point of rejection or success.
Exception patterns that indicate an attack attempt, not a benign bug. Deserialization exceptions happen in normal operation too (a version-skew bug, a genuinely malformed message from a misbehaving upstream), so the signal is in the pattern, not any single exception:
InvalidClassExceptionor a serialization-filter rejection citing a class name that is not, and has never been, part of the application's own type set. A legitimate version-skew issue cites a class the application does know about, just with an incompatibleserialVersionUID; an attack attempt typically cites a class the application never declared as expected at all.ClassCastExceptionimmediately following a successfulreadObject()call with no filter present (a "cast happens too late" pattern, where the object is fully reconstructed, magic methods included, before the code discovers it is the wrong type): this specific sequence, successful deserialization followed immediately by a cast failure to the expected type, is a strong indicator of exactly this vulnerability class being exercised, whether or not the specific attempt succeeded in achieving anything further.- A burst of distinct exception types or resolved class names from the same call site in a short window, suggesting an attacker iterating through a candidate gadget-chain catalogue rather than a single, consistent upstream bug (which would typically produce the same exception repeatedly).
Profiling metrics to capture. These catch attempts that do not throw at all, either because the chain partially succeeds or because a well-formed-but-hostile object graph is still being processed:
- Wall-clock and CPU time spent inside the deserialization call itself, flagged against a per-call-site baseline (a legitimate
InternalTypepayload deserializes in a narrow, predictable time range; an attacker exploring a deep or wide object graph, or one whose reconstruction triggers expensive incidental work like aLazyMap/hashCodechain trigger invoked during a Java gadget chain, will often deviate measurably). - Object allocation count/heap growth attributable to a single deserialization call, since a resource-exhaustion-oriented payload (deliberately deep or self-referential object graphs) shows up here even when it never throws an exception at all.
- Stack depth at the point of any exception thrown during deserialization: an unusually deep call stack is consistent with a multi-hop gadget chain (several classes' methods calling into each other) rather than a normal, shallow deserialization failure.
Sampling strategy to avoid overloading the system. The core tension: deserialization is comparatively rare per-request but the interesting events are rarer still within that already-small population, so a strategy has to avoid both "log everything in full detail" (unsustainable overhead on a busy service) and "sample at a fixed low rate" (which can simply miss the one attack attempt in ten thousand normal calls). The resolution is tiered, not uniform:
- Always emit the lightweight structured event (outcome, resolved type, caller identity) for every deserialization call, at effectively negligible cost, since it is a handful of fields, not a payload capture.
- Capture full detail (stack trace, payload snapshot, profiling data) only on the anomalous subset: any rejection, any exception, any call exceeding the per-call-site timing/allocation baseline by a defined margin. Because that subset is a small fraction of total traffic under normal conditions, the expensive capture path essentially never runs against legitimate traffic and cannot become an overload vector on its own, unless the service is actively under attack, in which case the elevated capture rate is itself informative and should be allowed to run, with a hard cap (rate-limited capture, dropping the least-informative duplicate events first) protecting against a sustained flood specifically designed to exhaust the logging pipeline itself.
- Down-sample only within a single repeating pattern, not across distinct ones: if the same call site produces the identical rejection (same source, same rejected class name) thousands of times in a short window, capture full detail on the first several occurrences and then switch to a lightweight counter increment for the remainder of that specific pattern, while still capturing full detail immediately if a different pattern (a new class name, a new source) appears. This preserves forensic value on genuinely new signal while bounding cost from a single noisy, already-understood source.
Automated mitigations to trigger. Tiered by confidence, so a single ambiguous signal never triggers the same response as a corroborated one:
- High confidence (a filter rejection citing a class from a known gadget-chain catalogue, or the cast-too-late exception pattern specifically): rate-limit or temporarily block the originating identity automatically, and alert immediately with the full captured detail attached.
- Medium confidence (an unrecognized class name rejected, but not matching a known-dangerous catalogue entry, or a single timing/allocation anomaly with no corroborating exception): log for aggregation and review; a single occurrence is not actionable alone, but repeated occurrences from the same source should escalate automatically to the high-confidence response.
- Low confidence (an isolated exception matching a known, already-triaged benign cause like version skew from a specific internal consumer): suppress from paging entirely, but keep in the structured event stream, since a source that is normally benign starting to also produce high-confidence signals is itself a meaningful change worth being able to see in the aggregate data.
Short-term detection heuristics versus longer-term developer fixes. These serve different purposes and should not be conflated in how they get reported: heuristics buy visibility now, while the underlying code needs its own fix regardless of how good the detection gets.
- Short-term: deploy the structured logging and the exception/profiling heuristics above against the current, unmodified deserialization code, since instrumentation can usually ship without touching the vulnerable call site itself, which is exactly why it is the fast, low-risk first move.
- Longer-term: the actual code-level and runtime fixes (type-allowlisting filters, migration to a non-executable serialization format) remain necessary; detection alone does not close the vulnerability, it only shortens the time between an attempt and a response. A team that ships excellent detection and stops there has built a very good alarm on a door that is still unlocked.
Worked example
Concretely: a payments service's order-processing endpoint deserializes an OrderUpdate object at a steady, well-characterized baseline volume, with a narrow, predictable range of CPU time and allocation count per call under normal conditions (the specific baseline numbers would come from that service's own profiling, not from a figure asserted here). An attacker begins probing with a sequence of different gadget-chain candidate classes; the first several attempts produce distinct InvalidClassExceptions citing class names never seen at this call site before (a strong signal on its own), and one attempt that happens to reference a class the filter has not yet been configured to reject produces a successful readObject() immediately followed by a ClassCastException, the cast-too-late pattern, with CPU time and allocation count for that single call falling well outside the site's normal profiled range. Each of these individually might be dismissed as noise; correlated together (multiple distinct rejected class names, then one cast-too-late exception, then an outlier resource-usage reading, all from the same source identity within a short window) they cross into high-confidence territory and trigger the automated response: the source identity is rate-limited immediately, and the full captured detail (which specific class names were attempted, the exact profiling anomaly) goes to the on-call responder rather than requiring them to reconstruct the sequence from raw logs after the fact.
Trade-offs and pitfalls
- Sampling at a fixed rate instead of tiering by anomaly. A flat 1% sample rate applied uniformly can easily miss a single, unique attack attempt buried in ordinary traffic, since the events that matter most here are rare by nature; tiering (lightweight-always, detailed-on-anomaly) is more work to build but is the only approach that does not trade away exactly the signal the instrumentation exists to catch.
- Treating every deserialization exception as an attack signal. Version-skew and genuinely malformed upstream messages produce real exceptions too; a detection system that pages on every occurrence trains the team to ignore the alert channel within days. The pattern-matching (unrecognized class names, the specific cast-too-late sequence, cross-source clustering) is what separates signal from routine operational noise, and skipping that discrimination is the fastest way to make an otherwise-good detection system worthless in practice.
- Building detection and never closing the underlying vulnerability. As stated above, this is the single most common way a good detection investment gets undermined: excellent visibility into an attack that remains fully capable of succeeding is a worse security posture than it appears on a dashboard, because "we would have seen it" is not the same claim as "it could not have worked."
- Capturing full payload snapshots on every anomalous event without limits. Even the "anomalous subset only" capture path can be flooded deliberately by an attacker who understands the system is instrumented this way, sending a sustained stream of distinct rejection-triggering payloads specifically to exhaust logging storage or downstream SIEM (Security Information and Event Management) ingestion capacity; the rate-limited, deduplicating fallback described in the sampling strategy exists specifically to bound this, and omitting it is a real operational risk, not a theoretical one.
Explain secure error-handling and logging practices in application code. Describe what information should never be logged or shown to users (plaintext secrets, full stack traces, internal paths), and how logging, UI error messages, and exception handling should each be treated differently.
Sample Answer
Direct answer
Logging, user-facing error messages, and internal exception handling serve three different audiences (operators, end users, and the code itself), so each one needs a different filter on what it is allowed to contain. The one rule that governs all three: anything an attacker could use directly (a password, a session token, a private key) or use to map out the system (a stack trace, a file path, a database schema hint) never leaves the server boundary in a form a user or the public internet can read. What operators need for debugging is not the same as what a user needs to recover, and neither should ever be a raw dump of what the program was doing internally.
Structured elaboration
What must never be logged or shown to anyone outside the trusted operations team
- Plaintext secrets: passwords, API keys, full session tokens, credit card numbers, private keys. If a value can authenticate as someone or decrypt something, it does not belong in a log line, even one only operators can read, because logs get shipped to third-party aggregators, get grepped by many engineers, and get retained far longer than the secret's intended lifetime.
- Full stack traces shown to the user or returned in an API response body. A stack trace reveals the framework version, internal file paths, class and method names, and sometimes a fragment of a SQL query or config value that ended up in an exception message. That is a free reconnaissance map for an attacker.
- Internal paths: server file-system layout, internal hostnames, internal IP addresses, environment names. None of this helps a legitimate user and all of it helps an attacker chain a partial exploit into a working one.
Why the three consumers need different treatment
| Consumer | Purpose | What it should contain | What it must never contain |
|---|---|---|---|
| Logs (for operators/on-call) | Diagnose and fix the problem after the fact | Structured event data: timestamp, service name, a correlation ID, the error type, sanitized/redacted context | Plaintext secrets, raw personally identifiable information (PII), unredacted stack traces from third-party libraries that might echo input |
| UI error message (for the end user) | Tell the user what to do next without confusing or exposing them | A short, human sentence plus an error code and, ideally, the same correlation ID that appears in the log line | Any implementation detail: exception class names, SQL fragments, internal service names, stack traces |
| Exception handling (inside the code) | Let the program fail safely and recover or fail closed | The full, unredacted exception object, in memory, available to the catch block that decides what to log and what to show | Nothing extra here, this is the one place the full detail is legitimate. The discipline is making sure it never crosses the boundary out of this layer unfiltered |
The pattern that keeps these three from bleeding into each other: catch the real exception close to where it happens, log a sanitized structured event from it (never the object's default string form, which often is the stack trace), generate a short opaque error code, and return only that code and a generic message to the caller. The correlation ID or error code is the bridge: a user reports "error PAY-402" to support, and support (or an on-call engineer, not the user) looks up PAY-402 in the log system to see the real, unredacted detail.
Sanitizing before it hits the log line
- Redact or mask known-sensitive fields with an allowlist-based logging wrapper, not a denylist you have to remember to update: log only fields you have explicitly approved (user ID, order ID, error type), rather than logging "everything on the request object" and trying to strip out the bad parts after the fact.
- For values you need to correlate but cannot store raw (a card number, an email), store a keyed hash or a masked form (
**** **** **** 1234) instead of the raw value. - Apply the same discipline to error messages coming from dependencies. A database driver's exception message can itself contain the query and, occasionally, a parameter value. Wrap and re-throw a sanitized application-level exception rather than letting the raw driver exception propagate to the log or the response.
Worked example
A payment endpoint calls out to a card processor and the call times out because of a misconfigured internal DNS entry.
- Inside the code (exception handling layer): the HTTP client throws
SocketTimeoutException: connect timed out: internal-payments.svc.cluster.local:8443. This is caught immediately at the call site, not left to bubble up to a generic top-level handler. - What gets logged:
{"ts": "2026-07-27T10:02:11Z", "level": "ERROR", "service": "checkout", "correlation_id": "8f2e-91ac", "event": "payment_gateway_timeout", "order_id": "ord_5521", "downstream": "payment-gateway"}. Notice the internal hostname and the raw exception class are gone; "downstream: payment-gateway" is enough for an operator to know where to look, without publishing the internal DNS name. - What the user sees: "We couldn't process your payment. Please try again, or contact support with code PAY-402 (reference 8f2e-91ac)." No mention of DNS, timeouts, or internal service names.
- What support does: they take the reference
8f2e-91ac, search the log system, and land on the full structured event from step 2, which is enough to tell them this is an infrastructure problem, not something the customer did wrong.
This is the general shape for any error: the exception layer sees everything, the log sees a sanitized structured version of it plus a correlation ID, and the user sees a short generic message plus that same correlation ID as their key to get help.
Trade-offs and pitfalls
- Logging the exception's default
toString()/str()output "for convenience." This is the most common way secrets and stack traces end up in logs: a developer logslogger.error(e)instead of a hand-built structured event, and whatever the exception's default representation includes (which can vary by library and change on a dependency upgrade) goes straight into the log store. - Debug mode left on in production. Frameworks that render a full stack trace as an HTTP response in development are extremely convenient for developers and extremely dangerous if that flag ships to production. Verify this is environment-gated and tested, not just documented.
- Over-correcting into unhelpfully vague logs. The fix for "don't log secrets" is not "log nothing useful." A log with only
"an error occurred"and no correlation ID, order ID, or error type is nearly as unproductive during an incident as a log full of secrets is dangerous. Structured, sanitized, and specific is the target, not sparse. - Forgetting third-party and dependency logs. Your own code can be disciplined about this while a logging middleware, an ORM's query logger, or an API gateway's access log quietly captures full request bodies (including passwords in login requests) at a layer you don't control by default. Audit what every layer in the request path logs, not just your own application code.
- Treating the correlation ID as sensitive. It is not a secret, it is a lookup key, and hiding it from the user defeats the point of giving them a way to reference their specific failure when they contact support.
You discover a critical SQL injection in a decade-old legacy application. Management offers several alternatives: an immediate WAF rule as a stopgap, patching the query-string building directly, migrating to an ORM in the medium term, or isolating the app with network controls. Analyze each option's pros, cons, verification steps, and rollback risk, and recommend a phased remediation plan.
Sample Answer
Direct answer: For a critical SQL injection in a decade-old legacy app, the right call is almost never a single option in isolation - deploy the WAF rule immediately as a stopgap while you patch the actual query, because the four options operate on completely different timescales and risk profiles, not as mutually exclusive choices.
Structured elaboration, option by option:
1. Immediate WAF rule. Pros: deployable in minutes, no code change, no regression risk to the application itself. Cons: a signature-based rule can be evaded (encoding tricks, comment injection, alternate syntax) and gives false confidence if treated as "fixed." Verification: confirm the specific payload that triggered the finding is now blocked, and test a couple of known evasion variants against the rule. Rollback risk: near zero - disabling a WAF rule is instant and doesn't touch application state.
2. Patch the query-string building. Pros: fixes the actual root cause; this is the only option on the list that structurally closes the vulnerability rather than reducing its likelihood of exploitation. Cons: requires a code change, a deploy, and regression testing on a decade-old codebase that may have thin test coverage around this code path. Verification: the exact reproduction steps from the vulnerability report should return the expected safe result after the fix (as demonstrated for the classic pattern: a parameterized version of a vulnerable query returns zero rows for an injection payload that previously leaked every row). Rollback risk: moderate - a badly-tested change to old, brittle code can introduce a functional regression, so this needs real test coverage or careful manual verification before it ships to production.
3. Migrate to an ORM, medium-term. Pros: prevents this whole CLASS of bug going forward across the codebase, not just this one query. Cons: a large, slow, high-risk undertaking on a decade-old app; doing this under incident pressure invites new bugs from a rushed migration. This is a program of work, not an incident response action. Verification: this needs its own testing program, not a quick check. Rollback risk: high if rushed - this is exactly the kind of change that should happen on a normal engineering cadence, not as part of the immediate incident response.
4. Isolate the app with network controls. Pros: reduces exposure (fewer things can reach the vulnerable endpoint) without touching the vulnerable code at all. Cons: doesn't fix anything if the attack surface is still reachable by legitimate users who need it; only genuinely useful if the app can be taken off the public internet or restricted to a smaller trusted network without breaking its actual purpose. Verification: confirm the network change doesn't also break legitimate traffic. Rollback risk: low, but "isolating" a production app that customers need to reach isn't always a real option.
Recommended phased plan: (1) WAF rule live within the hour as a stopgap, verified against the specific reported payload; (2) patched query shipped within days, with the specific exploit payload from the report added as a permanent regression test; (3) network isolation considered in parallel only if it doesn't disrupt legitimate use, as extra defense in depth while (2) is in flight; (4) ORM migration scheduled as its own project, informed by this incident but not rushed because of it.
Trade-offs and pitfalls: the single biggest mistake here is treating the WAF rule as the fix and closing the incident - it buys time, nothing more, and a determined attacker will eventually find the encoding variant it doesn't cover. The second biggest mistake is rushing the ORM migration under incident pressure; a decade-old codebase's untested corners are exactly where a rushed migration introduces a NEW, unrelated bug.
During a targeted code review, what patterns and code constructs would you look for to quickly identify injection risks such as SQL injection, command injection, and LDAP injection? Provide a short checklist and concrete examples of risky constructs to prioritize.
Sample Answer
Direct answer
The pattern that unites SQL injection, command injection, and LDAP injection is the same shape: untrusted input is concatenated or interpolated directly into a string that is then interpreted by another sub-language (SQL, a shell, an LDAP filter), rather than being passed as a separate, clearly-delimited data value. During a review, the fastest way to find these is to search for exactly that shape: string concatenation or formatting feeding into a query-execution, process-execution, or directory-search call, and to prioritize anywhere that construct touches a request parameter, header, or other externally-controlled value.
Structured elaboration
The short checklist, in priority order
- Unsanitized string concatenation or interpolation of user input into a query, command, or filter string.
- Use of a "raw execute" API (a query method that takes a plain string) where a parameterized or prepared-statement equivalent exists and is not being used.
- Direct calls into a shell (
os.system,subprocesswithshell=True, backticks,exec/eval) fed by anything derived from user input. - Manual escaping logic written by hand instead of using the platform's parameterization or a maintained escaping library, since hand-rolled escaping reliably misses edge cases.
- Error handling that swallows a database or LDAP error rather than surfacing it, which can hide evidence that a payload reached the interpreter and mask early testing signals.
What each injection class looks like in code, concretely
-
SQL injection. The classic tell is a query built with
+, string formatting, or an f-string/template literal that includes a variable sourced from user input:javaString q = "SELECT * FROM users WHERE id = " + request.getParameter("id");php$db->query("SELECT * FROM posts WHERE title = '$title'");The fix is a parameterized query or prepared statement, where the value is passed as a bound parameter, not woven into the SQL text:
PreparedStatementin Java,?/named placeholders in PDO for PHP, or an ORM's parameterized query builder used correctly (an ORM does not automatically prevent this if a raw-query escape hatch is used with concatenated input). -
Command injection. The tell is user input reaching a function that invokes a shell or spawns a process, especially with shell interpretation enabled:
pythonos.system("ping -c 1 " + host) subprocess.Popen("sh -c '" + cmd + "'", shell=True)The fix is avoiding shell invocation entirely when possible (pass arguments as a list to
subprocess.run([...], shell=False)rather than building a shell command string) and strictly allow-listing acceptable input (for thepingexample, validating thathostis a well-formed hostname or IP address before it is used at all, rather than trying to escape it for shell safety). -
LDAP injection. LDAP (Lightweight Directory Access Protocol) is the protocol many enterprise systems use to query a directory service, such as Active Directory, for user, group, and permission records, often as part of authentication - so an LDAP injection targets that directory lookup the same way a SQL injection targets a database. The tell is a filter string built by directly interpolating user input into the search filter syntax:
javaString filter = "(uid=" + username + ")"; ctx.search(base, filter, controls);Against this single-clause filter the smallest effective payload is a bare
*, which turns(uid=alice)into(uid=*): a syntactically valid filter that matches every entry in the directory instead of one. The longer OWASP-style payload*)(uid=*))(|(uid=*belongs to the two-clause bind filter(&(uid=USER)(userPassword=PASS)), where it closes the intended conjunction early and leaves the password clause stranded in an ignored trailer. Either way the point is the same: unescaped input manipulates the filter's logical structure the way a SQL injection payload manipulates a WHERE clause, so match the payload to the filter you are actually testing rather than reusing one from a different filter shape. The fix is LDAP-specific escaping of special filter characters (*,(,),\, the null character) using the platform's LDAP-escaping utility, or building the filter through an API that handles this for you rather than string concatenation.
Prioritizing findings during the review
Work in the order the checklist above lists: first flag any construct that concatenates unvalidated input directly into a SQL, shell, or LDAP context, since these are the highest-confidence, highest-impact findings. Second, look for APIs used with a "raw" or "unsafe" flag or method name, since these are often an escape hatch a developer reached for under time pressure. Third, review any custom escaping code, since hand-written escaping is a common source of subtle bypasses that automated scanners also frequently miss. Fourth, check that authentication and authorization checks actually gate the vulnerable code path, since an injection finding behind a properly enforced admin-only boundary is lower severity than the same finding reachable by any authenticated user.
Worked example
Reviewing a pull request for a feature that accepts and stores user-submitted comments on a blog post:
def save_comment(post_id, author, body):
query = f"INSERT INTO comments (post_id, author, body) VALUES ({post_id}, '{author}', '{body}')"
db.execute(query)
Applying the checklist: item 1 fires immediately, this is exactly the concatenation shape being searched for, with author and body (both fully attacker-controlled from the comment submission form) interpolated directly into the SQL text. A comment body of '); DROP TABLE comments; -- demonstrates the injection during testing: the interpolated string becomes INSERT INTO comments (post_id, author, body) VALUES (1, 'alice', ''); DROP TABLE comments; --'), which on any driver that permits multiple statements inserts an empty comment and then drops the table, with the trailing -- commenting out the leftover '). The payload has to be written for the column position it lands in: the same attack aimed at author instead needs the extra ', prefix (', ''); DROP TABLE comments; --) so that the VALUES list still supplies exactly three values, and getting that count wrong makes the statement fail with a column-count error before the injected command ever runs. The fix:
def save_comment(post_id, author, body):
query = "INSERT INTO comments (post_id, author, body) VALUES (?, ?, ?)"
db.execute(query, (post_id, author, body))
using a parameterized query so author and body are always treated as data values, never as SQL syntax, regardless of their content.
While reviewing this same code path, it is also worth flagging (as a separate, related finding, not a substitute for the SQL injection fix above) that stored user comments are a classic surface for stored cross-site scripting: if body is later rendered back to other users without output encoding, an attacker's comment content executes as script in every visitor's browser who views it. That is a distinct vulnerability class from the injection issues this checklist targets (it is about how output is rendered, not how a query or command is built) and is worth a second, separate check on the rendering side of the same feature rather than folding it into the SQL-injection fix itself.
Trade-offs and pitfalls
- Trusting an ORM as automatic protection. Most object-relational mapping (ORM) frameworks parameterize queries built through their standard query API, but nearly all of them also expose a raw-query or raw-SQL escape hatch for cases the ORM cannot express; a review has to check whether that escape hatch is used, and if so, whether it is fed with concatenated input.
- Escaping instead of parameterizing. Manually escaping quotes or special characters before concatenation is a much weaker and more error-prone defense than parameterization, because it depends on correctly anticipating every dangerous character and context (encoding, nested quoting, database-specific escape rules); prefer parameterization wherever the API supports it.
- Allow-listing after the fact instead of at the boundary. Validating input format (a hostname pattern, a numeric ID) is a strong complementary control for command injection specifically, but it needs to happen before the value is used, not as an afterthought review comment; a reviewer should confirm the validation actually gates the dangerous call, not just exists somewhere nearby in the file.
- Only reviewing the obviously "risky-looking" files. Injection risk shows up anywhere a query, command, or filter is built, including in less obvious places like logging statements that shell out, health-check endpoints, or admin tooling that is assumed to be low-risk because it is "internal only."
- Treating a clean grep as proof of absence. A quick search for
+ request.or similar patterns catches the obvious cases but misses injection reached through several layers of function calls, a shared utility that builds a query dynamically, or input that arrives through a header or cookie rather than an obvious request parameter; pair pattern search with tracing how untrusted input actually flows through the codebase for anything the checklist's first pass does not immediately clear.
A JSON-based API echoes a user-supplied parameter into a JavaScript client response inside a single-page application. Describe how you would test for DOM-based XSS: what instrumentation you would use (browser devtools, a Burp extension, automated DOM-sink scanning), a safe proof-of-concept payload skeleton, and how you would triage and classify the finding.
Sample Answer
Direct answer: Testing for DOM-based XSS means tracing the path from an attacker-controllable "source" (a URL parameter, location.hash, document.referrer, a postMessage payload) through the application's JavaScript to a dangerous "sink" (innerHTML, document.write, eval, setAttribute('onclick', ...)) and confirming the browser actually executes injected script when that path is exercised, since the server-side response here is only the messenger, not the vulnerable code.
Instrumentation and approach:
- Browser devtools first: open the page, search the rendered DOM and the page's JavaScript sources for the API in the response (here, the SPA reads a JSON API response and writes a field into the page). Set a DOM breakpoint ("break on subtree modification") on the container element, or use the Sources panel to step through the render function and see exactly which sink receives the value.
- Automated DOM-sink scanning: tools like a Burp Suite extension (e.g. DOM Invader) or a headless-browser crawler that hooks
innerHTML/document.write/evalat the JS engine level and reports every reachable source-to-sink flow, which is far faster than manually reading minified bundles. - Manual confirmation with a benign marker payload: before trying anything that executes, submit a distinctive string like
XSSPROBE12345as the parameter and confirm via devtools exactly where and how it lands in the DOM (as text, as an attribute, inside a script block). This tells you which encoding context you're up against before you craft a working payload.
Worked example / safe PoC skeleton. If the API response field is written via element.innerHTML = data.username, a proof-of-concept payload is <img src=x onerror=alert(document.domain)> submitted as the username - innerHTML parses this as real markup, the broken src triggers onerror, and alert(document.domain) fires, which is safe (no data exfiltration) but conclusively proves script execution. For a production engagement, swap alert(document.domain) for a non-destructive callback to a controlled logging endpoint you own, so you get a timestamped hit log rather than a visible popup that could alarm real users if the payload somehow reaches one.
Triage and classification once confirmed: record the exact source (which parameter/API field), the exact sink (which DOM write), and whether any encoding or sanitizer sits between them (many teams have a sanitizer library available but simply didn't call it on this particular field). Classify severity by what an attacker gains: session-cookie theft is high severity even without HttpOnly bypass tricks, since most SPAs also keep sensitive data in memory/localStorage that JavaScript CAN read directly.
Trade-offs and pitfalls: minified/bundled production JavaScript makes manual source-reading slow; work from source maps if available, or from the unminified dev build. A payload that works in Chrome devtools may be blocked by the site's CSP in production, so validate against the actual deployed headers, not just the sink's existence, before reporting severity. And a sink alone is not a finding: if the value is hard-coded or only ever set from a trusted internal source, there's no reachable "source," so always confirm the taint actually originates from something the attacker can control.
Unlock Full Question Bank
Get access to all Secure Coding and Application Security interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.