What this quiz covers
This quiz focuses on Xss And Mitigations, giving you a quick way to practice the rules, question types, and explanations that matter most for Cyber Security.
A single-page application reads the URL fragment and displays it as a page heading using heading.innerHTML = location.hash.substring(1). Requests containing a malicious fragment do not include that fragment in the HTTP request sent to the server.
Which assessment and remediation are most accurate?
textContent when it is intended to be displayed literally.<script> elements from the fragment before continuing to use innerHTML.Cyber Security Quiz
Practice Xss And Mitigations in Cyber Security with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.
This quiz focuses on Xss And Mitigations, giving you a quick way to practice the rules, question types, and explanations that matter most for Cyber Security.
Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.
A single-page application reads the URL fragment and displays it as a page heading using heading.innerHTML = location.hash.substring(1). Requests containing a malicious fragment do not include that fragment in the HTTP request sent to the server.
Which assessment and remediation are most accurate?
textContent when it is intended to be displayed literally. (correct answer)<script> elements from the fragment before continuing to use innerHTML.location.hash) is never sent to the server in HTTP requests, yet the application writes it directly into the DOM via innerHTML. That's the textbook definition of DOM-based XSS — a dangerous source (location.hash) flows into a dangerous sink (innerHTML). The correct fix, as C states, is to use textContent instead of innerHTML when displaying plain text. textContent treats the value as a literal string, so <img src=x onerror=alert(1)> renders as visible text rather than executing as HTML.
A is wrong on both counts: the fragment never reaches the server, so server-side URL-encoding is irrelevant and the classification as reflected XSS is incorrect. B misclassifies it as stored XSS — nothing is being persisted to session storage in this scenario — and the suggested fix addresses a problem that doesn't exist here. D correctly identifies DOM-based XSS but proposes an inadequate blocklist fix: stripping <script> tags misses dozens of other injection vectors like event handlers (onerror, onload) and javascript: URIs. Blocklist sanitization is notoriously incomplete.
Your study tip: memorize the source-to-sink flow for DOM XSS. Whenever you see location.hash, document.URL, or document.referrer feeding into innerHTML, document.write, or eval, that's DOM-based XSS — and textContent is your go-to safe sink.A security team deploys Content-Security-Policy-Report-Only with a policy that would block unauthorized inline scripts. During testing, an injected inline payload still executes, and the browser sends a violation report to the configured endpoint.
What is the best interpretation of this result?
Content-Security-Policy headers, the first thing to identify is which mode is active — enforcement or reporting. This distinction is the entire point of this scenario.
Content-Security-Policy-Report-Only is a diagnostic header, not an enforcement mechanism. When deployed, the browser evaluates your policy rules, identifies what would have been blocked, and sends violation reports to your designated endpoint — but it never actually prevents the content from executing. This is intentional: it lets security teams safely test a new policy in production without breaking legitimate functionality while they tune the rules. So the inline script executing and a report being generated is exactly correct behavior, making B the right answer.
A is wrong because it assumes report-only mode behaves like enforcement mode — it doesn't. A violation report in report-only mode is purely informational; no blocking ever occurs. The browser hasn't malfunctioned; it's working precisely as designed.
C is wrong because CSP absolutely can restrict inline JavaScript — that's one of its primary use cases. Directives like script-src 'nonce-...' or script-src 'strict-dynamic' block unauthorized inline scripts when the policy is enforced, not just reported.
D is a fabricated distractor. Violation reports have nothing to do with output encoding, and browsers don't "decode after validating." This option mixes unrelated concepts to sound plausible — a classic trap.
For the exam, remember: Content-Security-Policy enforces; Content-Security-Policy-Report-Only only observes. If you see "report-only," execution is always permitted regardless of violations detected.A site has a nonce-based CSP that successfully prevents an injected <script> element from executing. However, an attacker can still inject arbitrary HTML into the middle of a trusted page, including forms, links, and misleading page content.
Which statement best characterizes the remaining risk?
<script> tags from running, but an attacker who can inject arbitrary HTML can still do serious damage without JavaScript: spoofing login forms to harvest credentials, inserting misleading UI elements, redirecting users via injected links, or defacing page content. These are HTML injection attacks, and the defense against them is contextual output encoding — escaping characters like <, >, and " so injected content is rendered as text, not markup. CSP and encoding are complementary controls, not substitutes for each other.
A is dangerously wrong because it assumes JavaScript execution is the only meaningful threat from HTML injection. Content spoofing, phishing via injected forms, and UI redressing are all real attacks that require zero JavaScript. B is backwards — output encoding fixes the injection sink at the source, which is a security necessity, not a performance optimization. CSP doesn't "repair" the sink at all; it only limits one class of exploit. C describes a fundamental misconception: nonces are explicit attributes on trusted elements, not inherited properties. An attacker's injected <script> would have no nonce, so the browser blocks it — but non-script elements like <form> or <a> don't use nonces at all.
The key pattern to remember: defense-in-depth questions often test whether you understand that one control closing one attack vector still leaves others open. Always ask, "What does this control specifically address — and what falls outside its scope?"A profile page places a user-controlled display name in two locations: as visible text inside a <span> element and inside an inline JavaScript event handler. The application applies HTML entity encoding to the value once when it is stored in the database, then reuses that stored value in both locations.
Which change most directly addresses the underlying XSS risk?
script, then render all remaining values without additional output encoding.<span> content, you apply HTML entity encoding. For the inline JavaScript context, you apply JavaScript string escaping. Better still, B recommends replacing the inline handler entirely with a programmatic event listener (e.g., addEventListener), which eliminates the JavaScript-context injection risk altogether. This is defense-in-depth applied correctly: context-aware output encoding plus a safer architectural pattern.
A is tempting but wrong — double-encoding angle brackets doesn't make a value safe in a JavaScript context, because JavaScript doesn't interpret HTML entities. You're solving the wrong problem twice.
C fails because URL encoding is designed for URL components, not HTML text or JavaScript strings. Applying it universally and expecting browsers to "sort it out" is not a security strategy — it introduces decoding inconsistencies that attackers can exploit.
D represents an input validation approach, which is a useful layer but never a substitute for output encoding. Blocklists are notoriously incomplete; attackers bypass them constantly using encoding tricks, Unicode, or event handlers that don't involve <script> at all. Rendering without output encoding after a blocklist check is still dangerous.
Your takeaway: always ask where data is being output, not just when it was encoded. Context determines the correct encoding scheme.A search page immediately includes the current q query parameter in its HTML response. A gateway removes the exact substring <script>, but a tester submits an image element with an error event handler and causes JavaScript to execute. The value is not stored by the application.
Which classification and primary remediation are most appropriate?
<img> tag with an onerror handler (e.g., <img src=x onerror=alert(1)>), which executes JavaScript even though the gateway strips the literal string <script>. This reveals the fatal flaw of blacklist/substring filtering: attackers simply route around the blocked pattern. The correct fix is output encoding — converting characters like <, >, and " into their HTML entity equivalents at the point of rendering, so the browser never interprets the input as markup regardless of its structure. That's exactly what A describes, making it the right answer.
B is wrong on both counts: this isn't stored XSS (nothing is written to a database), so purging records and rotating sessions addresses a threat that doesn't exist here.
C misclassifies the attack as DOM-based XSS, which occurs when client-side JavaScript writes attacker-controlled data to the DOM without a server round-trip. That isn't happening here — the server is generating the vulnerable HTML response.
D correctly identifies reflected XSS but proposes expanding the blacklist. This is a trap: blacklists are inherently incomplete. Blocking <img> still leaves <svg>, <details>, <body> event handlers, and countless other vectors untouched.
Your study tip: whenever a question describes bypassing a filter, that's a signal that the remediation must be structurally sound (encoding, parameterization, CSP) — not a bigger filter.A discussion site intentionally permits users to submit limited formatting, including links, emphasis, and lists. The current implementation inserts submissions with innerHTML. Product requirements state that approved formatting must continue to render rather than appear as literal markup.
Which defensive design best meets both the security and functionality requirements?
innerHTML, and rely on the browser to restore approved formatting.<script> tags and inline event handlers, then permit all remaining elements, attributes, and URL schemes.innerHTML, then disable browser error messages.innerHTML is then safe because dangerous constructs have already been removed. Layering Content Security Policy on top adds defense-in-depth, blocking any bypass that might slip through. This satisfies both requirements: approved formatting renders, and malicious payloads are neutralized.
Option B fails because HTML-encoding escapes all markup — angle brackets become < and > — so the browser displays tags as literal text rather than rendering them. This breaks the functionality requirement entirely; your <em> and <a> tags appear on screen as symbols.
Option C is a classic blocklist trap. Blocking only <script> and inline handlers leaves dozens of attack vectors open: <img onerror=...>, javascript: URLs in href, SVG-based payloads, and more. Blocklists are fundamentally incomplete.
Option D conflates two different escaping contexts. JavaScript-string escaping prevents breaking out of a JS string literal — it has no meaningful effect on HTML parsing inside innerHTML. This provides essentially no XSS protection.
The study takeaway: whenever you see "allow some HTML but stay secure," the answer is almost always allowlist sanitizer + CSP, never blocklists or misapplied escaping.A template creates a link with <a href="USER_VALUE">Open</a>. The template engine correctly HTML-attribute-encodes quotes, angle brackets, and ampersands in USER_VALUE. An attacker supplies a value beginning with javascript: that contains no quote or angle-bracket characters.
What additional defense is most appropriate for this sink?
HttpOnly so the browser refuses to navigate to script-based link targets.javascript while permitting all other URI schemes accepted by the browser.javascript: URI contains no quotes or angle brackets, so attribute encoding passes it through untouched — the browser happily executes it when the user clicks the link.
The right fix, answer D, is an allowlist validation on the URI scheme before encoding. By permitting only safe schemes like https:// or http://, you eliminate the entire class of script-execution URIs at the input stage. Normal attribute encoding is still applied afterward to handle any remaining special characters. Defense-in-depth: validate what the value means, then encode how it is rendered.
Answer A is wrong because double-encoding garbles the URL for legitimate users and doesn't prevent navigation to dangerous targets — it just changes how the characters look, not what the browser does with them.
Answer B is wrong because HttpOnly prevents JavaScript from reading cookies via document.cookie; it has absolutely no effect on whether a browser follows a javascript: link. These are completely separate security mechanisms.
Answer C is wrong because blocklisting is fragile. Attackers can bypass simple string removal with variations like javascript\t:, javascript:, or browser-quirk exploits. Blocklists on URI schemes are notoriously incomplete.
Study tip: Whenever a sink involves user-supplied URLs, ask two separate questions — "Is this scheme safe?" (validation) and "Are the characters encoded?" (encoding). Both layers are necessary, and neither alone is sufficient.An application deploys Content-Security-Policy: script-src 'self'. Users can upload files that are later served from the same origin under /uploads/. An attacker finds an HTML injection flaw and uploads a file containing JavaScript that is served with a script-compatible content type.
Which conclusion is most accurate?
'self' permits application scripts but automatically excludes all user-uploaded resources.script-src 'self' directive permits any script served from the same origin as the page. That means if /uploads/malicious.js is served with a script-compatible MIME type from the same domain, the browser has no reason to block it — it passes the origin check. The policy cannot distinguish between a legitimate application script and an attacker's uploaded file if both share the same origin. This is why C is correct: the uploaded script may execute freely under 'self', and a stronger defense would isolate uploads on a separate origin (so they fail the 'self' check) or use nonce- or hash-based directives that require each legitimate script to be explicitly authorized.
A is the classic trap here — it assumes 'self' has some built-in awareness of which same-origin files are "application scripts." It doesn't. Any resource at the same origin qualifies.
B is completely fabricated. CSP has no concept of administrator authentication or authorship; it operates entirely at the HTTP response level without any user-identity awareness.
D confuses where scripts execute. Browser-side JavaScript runs in the client's browser, not on the web server. This isn't SSRF, which involves the server making outbound requests.
Your study tip: whenever you see 'self' in a CSP question, immediately ask yourself whether user-controlled content could be served from that same origin — that's the attack surface.A server serializes a user-controlled preference into an inline block: <script>window.settings = JSON_VALUE;</script>. The JSON serializer correctly escapes quotation marks for JSON strings but leaves < characters unchanged. A preference value can therefore contain </script> followed by attacker-controlled HTML.
Which remediation most directly addresses the parsing issue?
< in embedded JSON, or retrieve the data separately without placing it in executable markup. (correct answer)HttpOnly to the session cookie because the browser will then ignore closing script tags supplied by page data.<script> block, you're dealing with two parsers simultaneously: the HTML parser and the JavaScript parser. The HTML parser runs first and scans for </script> regardless of JavaScript context — meaning a user-supplied string containing </script> can prematurely close the script block and inject arbitrary HTML before the JavaScript engine ever sees the data. This is a classic script-injection via parser confusion vulnerability.
C is correct because it attacks the root cause: the < character (and </) must be escaped in JSON that lives inside HTML script blocks. Safe serialization patterns (like encoding < as \u003C) prevent the HTML parser from interpreting the sequence as a tag. Alternatively, fetching the data via a separate API call entirely avoids the problem by never placing user data in executable markup at all.
A is wrong because JSON embedded between <script> tags is not interpreted as an attribute value — HTML attribute encoding rules don't apply here and would not prevent the HTML parser from seeing </script>.
B is wrong because it misidentifies the threat. The closing-script vulnerability is recognized by the HTML parser, not the JavaScript parser, so escaping only quotation marks does nothing to prevent it. Base64-encoding quotes is also a non-standard and ineffective approach.
D is wrong because HttpOnly protects cookies from being accessed by JavaScript — it has absolutely no influence on how the browser parses HTML or handles closing script tags.
Study tip: Whenever user data appears inside a <script> block, ask yourself which parser sees it first — HTML always wins, so HTML-level escaping of < is mandatory regardless of what the JSON serializer does.An application has a stored XSS flaw in a comment field. Its session cookie is configured with the HttpOnly, Secure, and SameSite=Lax attributes. A victim views an attacker's comment while authenticated.
Which statement best describes the protection provided by these cookie attributes?
HttpOnly attribute.SameSite=Lax blocks requests initiated by page scripts.HttpOnly blocks JavaScript from reading the cookie via document.cookie, so the attacker cannot steal the session token and replay it elsewhere. Secure ensures the cookie only travels over HTTPS, preventing interception in transit. SameSite=Lax restricts the cookie from being sent with cross-site top-level navigations initiated by third-party pages. Together, these are meaningful defenses — but they share a critical blind spot: the malicious script is already running inside the victim's origin. From that position, it can call fetch() or XMLHttpRequest to make same-origin requests, and the browser will automatically attach the session cookie to those requests. The attacker can therefore trigger authenticated actions (changing passwords, submitting forms, exfiltrating data) without ever reading the cookie directly. That reasoning confirms C is correct.
A is wrong because HttpOnly prevents reading the cookie, not executing the injected script — the script still runs. B is wrong because SameSite=Lax only restricts cross-site requests; requests made by scripts within the same origin are unaffected. D is a fabrication — cookie attributes have no mechanism to change how or where a script payload is stored.
The key study tip: cookie security attributes are theft and cross-site defenses, not XSS execution defenses. A script already on your origin bypasses all of them for same-origin actions.