Cyber Security Quiz: Input Validation And Output Encoding
10 questions · exam conditions
0:00
Input Validation And Output EncodingQuestion 1 of 10

A profile value is displayed once as text inside a <div> and once inside a JavaScript string literal in a generated <script> block. The development team currently applies standard HTML entity encoding to the value in both locations.

Which assessment of this design is most accurate?

HTML encoding is sufficient because both locations are delivered in an HTML document.
Allowlist validation makes output encoding unnecessary in either of the two locations.
Each location requires encoding for its specific context, or the script insertion should be avoided.
JavaScript encoding should be applied first and then reused in both output locations.
← Back to quizzes

Cyber Security Quiz

Cyber Security Quiz: Input Validation And Output Encoding

Practice Input Validation And Output Encoding in Cyber Security with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on Input Validation And Output Encoding, giving you a quick way to practice the rules, question types, and explanations that matter most for Cyber Security.

How to use this quiz

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.

All questions

Question 1

A profile value is displayed once as text inside a <div> and once inside a JavaScript string literal in a generated <script> block. The development team currently applies standard HTML entity encoding to the value in both locations.

Which assessment of this design is most accurate?

  1. HTML encoding is sufficient because both locations are delivered in an HTML document.
  2. Allowlist validation makes output encoding unnecessary in either of the two locations.
  3. Each location requires encoding for its specific context, or the script insertion should be avoided. (correct answer)
  4. JavaScript encoding should be applied first and then reused in both output locations.
Explanation: When you see a question about output encoding and injection prevention, your first instinct should be to think in terms of rendering contexts. Every location where user-supplied data appears has its own syntax rules, and an encoding scheme designed for one context may be completely ineffective — or even dangerous — in another. In this scenario, the profile value appears in two distinct contexts: inside an HTML <div> element and inside a JavaScript string literal. HTML entity encoding (converting < to &lt;, " to &quot;, etc.) is designed to neutralize characters that carry meaning in HTML markup. However, inside a JavaScript string, the browser's JavaScript parser runs before HTML entity decoding in that context, meaning an attacker could inject characters like \, ', or " to break out of the string literal and execute arbitrary code — none of which HTML encoding would stop. Answer C is correct: each location demands context-appropriate encoding. The <div> needs HTML encoding; the script block needs JavaScript string encoding (or, better yet, the team should avoid injecting user data into script blocks altogether. Answer A is wrong because being "inside an HTML document" does not mean every location follows HTML parsing rules — script blocks follow JavaScript parsing rules, creating a separate injection surface. Answer B is wrong because allowlist validation and output encoding serve complementary, not interchangeable, roles; validation reduces what enters the system, but encoding protects each specific output context. Answer D is wrong because you cannot apply JavaScript encoding once and reuse it for HTML output — the two encoding schemes produce different results for different parsers. The key study tip: always map where data lands and ask "what parser processes this?" One encoding scheme per context, not one for the whole document.

Question 2

An application accepts a username, uses it in a database lookup, and later displays it in an HTML page. The proposed allowlist permits letters, digits, apostrophes, and hyphens because those characters occur in legitimate names.

Which control combination best addresses the two distinct uses of the username?

  1. Use parameterized SQL for the lookup and HTML-context encoding for the display. (correct answer)
  2. Apply HTML encoding before the lookup and store that encoded value for later display.
  3. Escape apostrophes before the lookup and remove hyphens before displaying the value.
  4. Use the allowlist for the lookup and rely on the browser to encode the display.
Explanation: When user-supplied data flows into multiple contexts — a database query and an HTML page — you need to ask: what does each context require to be safe? SQL injection and cross-site scripting (XSS) are distinct threats that demand distinct defenses applied at the right moment. Parameterized queries (also called prepared statements) neutralize SQL injection by separating the query structure from user data entirely — the database never interprets the username as SQL syntax. HTML-context encoding (converting <, >, ", &, etc. into their HTML entities) prevents the browser from interpreting user data as markup when it's rendered on the page. Answer A applies exactly the right tool to each threat at the right stage, which is why it's correct. Answer B encodes for HTML before the database lookup, meaning you're storing HTML-encoded data in the database and hoping it displays correctly later. This conflates two separate concerns, corrupts your stored data, and still doesn't properly protect the SQL layer — parameterization is the right SQL defense, not pre-encoding. Answer C manually escapes apostrophes as a SQL defense, which is fragile and incomplete (it misses many attack vectors), and arbitrarily stripping hyphens for display doesn't address XSS at all — it just breaks legitimate names like "Smith-Jones." Answer D relies on the browser to encode output, but browsers render HTML — they don't sanitize it on your behalf. Server-side output encoding is your responsibility, not the client's. The key study pattern: match the defense to the context. SQL belongs with parameterization; HTML output belongs with encoding. Never let one fix try to cover both threats.

Question 3

An identity system allows internationalized account names. It blocks a reserved name and enforces uniqueness by comparing the submitted text before Unicode normalization. A downstream component normalizes names before authorization decisions.

Which change best prevents inconsistent validation and comparison outcomes?

  1. Normalize to the chosen canonical form before reserved-name and uniqueness checks. (correct answer)
  2. Perform reserved-name checks before normalization but uniqueness checks after normalization.
  3. HTML-encode non-ASCII characters before comparing account names for authorization.
  4. Store every submitted byte sequence separately and normalize only when displaying names.
Explanation: When a system accepts internationalized text, the same visual string can exist in multiple byte representations — a classic Unicode normalization pitfall. Attackers exploit this by submitting a variant form that bypasses reserved-name or uniqueness checks, then having a downstream normalizer resolve it into the blocked or already-taken name. The defense is simple in principle: normalize first, then validate. Answer A is correct because applying normalization before reserved-name and uniqueness checks means every comparison operates on the same canonical form. There's no gap between what the intake layer sees and what downstream components produce — the security checks and the authorization logic speak the same language. Answer B is wrong because splitting the checks — reserved-name before normalization, uniqueness after — leaves a window open. An attacker could submit a variant that bypasses the pre-normalization reserved-name check, and if uniqueness is all that catches them afterward, a carefully crafted submission might still slip through. Consistency requires both checks to use the same normalized input. Answer C is a red herring. HTML-encoding is a defense against injection attacks in web output, not a solution to Unicode normalization inconsistency. It doesn't produce a canonical identity representation and would corrupt legitimate internationalized names. Answer D inverts the correct approach. Storing raw byte sequences separately and normalizing only for display means your security comparisons happen against un-normalized data, which is exactly the vulnerability you're trying to close. The study tip here: whenever you see a question involving internationalized input and validation, ask at what stage normalization occurs. If any security check runs before normalization, assume it can be bypassed.

Question 4

A web framework automatically HTML-encodes template variables. A developer also HTML-encodes user comments before saving them. When a user enters A & B, the page displays A &amp; B rather than A & B.

Which change best fixes the display problem without weakening the injection defense?

  1. Disable template encoding and continue storing the manually encoded comments.
  2. Decode every stored comment immediately before inserting it into the template.
  3. Store canonical text and let the template encode it once at the HTML sink. (correct answer)
  4. Add &amp; to an input denylist and reject comments containing ampersands.
Explanation: When dealing with output encoding, the golden rule is: encode data exactly once, at the point where it enters a new context (the "sink"). Double-encoding happens when data is transformed at multiple stages, causing literal escape sequences to appear instead of the intended characters. Here, the developer encodes & into &amp; before storing it, then the template engine encodes it again, turning &amp; into &amp;amp; — which renders visibly as A &amp; B instead of A & B. The fix is to store raw, canonical text (exactly what the user typed) and let the template's auto-encoding handle the conversion once at render time. That's precisely what C recommends: keep storage clean and trust the single, consistent encoding layer at the HTML sink. A is dangerous because disabling template encoding eliminates your primary injection defense entirely. The manually encoded stored data would render correctly, but any variable that skips manual encoding becomes an XSS vulnerability. B decodes stored comments before inserting them into the template, which sounds logical but creates a race condition of trust: you're now injecting decoded, potentially malicious content into the template, relying solely on the template engine catching everything. It also complicates the data pipeline unnecessarily. D blocking & on a denylist is a classic security anti-pattern. Denylists are incomplete by design — they break legitimate input and don't address the root cause (double-encoding), leaving you vulnerable to variants you didn't anticipate. The study tip: whenever you see encoding happening at both storage and rendering, suspect double-encoding. Always encode once, late, and at the sink.

Question 5

After login, an application redirects users to a returnUrl parameter. It permits a value when the raw string starts with https://portal.example.com. A tester supplies https://portal.example.com.attacker.test/path, which passes the check.

Which validation strategy most reliably enforces the intended redirect policy?

  1. HTML-encode the entire URL before passing it to the browser's redirect function.
  2. Reject URLs containing additional periods after the expected hostname text.
  3. Parse and canonicalize the URL, then require an approved scheme, host, and port. (correct answer)
  4. Require the expected hostname string to appear anywhere before the first path slash.
Explanation: Whenever you see a question about redirect validation, think about input validation bypass — specifically how string-matching shortcuts create exploitable gaps. The core issue here is that checking raw string prefixes is not the same as checking what a URL actually means structurally. The reason C is the correct strategy is that parsing and canonicalizing the URL first — then inspecting discrete components like scheme, host, and port — eliminates ambiguity entirely. A proper URL parser treats https://portal.example.com.attacker.test/path as having the hostname portal.example.com.attacker.test, which clearly doesn't match the approved host portal.example.com. You're comparing structured data, not raw substrings, so no amount of clever string crafting can forge a match. Looking at the distractors: A is a red herring — HTML-encoding prevents XSS injection but does nothing to validate where the redirect actually sends the user. The domain remains attacker-controlled after encoding. B is a fragile blocklist approach; attackers can bypass it through URL encoding, Unicode tricks, or other obfuscation, and blocklists are notoriously hard to make complete. D is essentially the same flawed prefix-check described in the passage itself, just phrased differently — requiring the hostname to appear "before the first slash" still allows portal.example.com.attacker.test to satisfy the check. As a study tip, remember: allowlists beat blocklists, and structural validation beats string matching. Any time a question offers a parsing/canonicalization approach versus a "look for this substring" approach for security validation, the structured approach is almost always correct.

Question 6

A document service accepts a user-supplied filename, rejects any input containing the literal substring ../, and then combines the value with /srv/docs/. The underlying platform decodes percent-encoded characters and resolves path segments before opening the file.

Which change most directly corrects the conceptual flaw in this validation design?

  1. HTML-encode the filename before combining it with the document directory.
  2. Canonicalize the path, then verify it remains within the intended directory. (correct answer)
  3. Reject additional traversal strings such as ..\\ and %2e%2e/.
  4. Validate the original string again after the file has been opened.
Explanation: When you see a question about input validation and file access, ask yourself: where in the pipeline does the security check happen, and can the input be transformed before it reaches the dangerous operation? That's the core issue here. The flaw in this design is denylist-based filtering applied to the raw input. The service blocks the literal string ../, but the underlying platform decodes and resolves paths after that check runs. This means an attacker can submit %2e%2e/secrets.txt — the filter sees no ../, passes the input, and then the platform decodes it into ../secrets.txt, enabling path traversal anyway. B is correct because canonicalization collapses all representations of a path — percent-encoding, double encoding, mixed slashes, redundant segments — into a single normalized form before the security decision is made. Once you have the resolved absolute path, you simply check whether it starts with /srv/docs/. This is a root-cause fix: you're comparing the path the OS actually uses against your intended boundary, regardless of how cleverly the input was encoded. A is wrong because HTML-encoding protects against cross-site scripting, not path traversal. It's solving a completely different vulnerability class. C expands the denylist but doesn't fix the architecture — it's whack-a-mole. Attackers can still bypass it with double encoding (%252e%252e/) or other variants you haven't anticipated. D is nonsensical from a security standpoint: validating after the file opens means the unauthorized access has already occurred. The study tip here: denylists fail against encoding tricks; allowlists and canonicalization win. Whenever a question offers "reject more bad patterns" versus "normalize then verify boundary," the latter is almost always the sounder design.

Question 7

A discussion site intentionally permits limited formatting in comments, including <strong> and safe hyperlinks. Encoding every angle bracket prevents script execution but also causes permitted markup to appear as literal text.

Which design best preserves the intended formatting while controlling active content?

  1. Decode HTML entities after rendering so permitted elements become active in the browser.
  2. Use a robust HTML sanitizer with allowlisted elements, attributes, and URL schemes. (correct answer)
  3. Reject the word script and render all remaining comment text as trusted HTML.
  4. Validate comment length and rely on a content security policy for safe rendering.
Explanation: When a web application needs to allow some HTML but block dangerous content, you're squarely in the territory of HTML sanitization — one of the most nuanced areas of web security. The core tension is this: you can't simply encode everything (which breaks intended formatting) or trust everything (which enables XSS). The real solution is surgical — allow known-safe elements and block everything else. Option B is correct because an allowlist-based HTML sanitizer does exactly this. It parses the input, keeps only explicitly permitted elements (like <strong>), strips everything else, enforces safe attributes, and restricts URL schemes (blocking javascript: hrefs, for example). This preserves legitimate formatting while neutralizing active content at the structural level. Option A describes a fundamentally backwards approach — decoding HTML entities after rendering reintroduces dangerous content that sanitization or encoding had already neutralized, essentially undoing your defenses at the worst possible moment. Option C is a classic blocklist trap. Rejecting only the word "script" is trivially bypassed with techniques like <scr ipt>, <SCRIPT>, or event handlers like onerror=. Blocklists can never anticipate every bypass; allowlists are far more reliable. Option D addresses symptoms rather than causes. Content Security Policy is a valuable defense-in-depth layer, but it's a browser-side mitigation — it doesn't sanitize the stored HTML. Validating length does nothing to prevent malicious payloads that fit within the limit. Study tip: On security exams, whenever you see an "allow some HTML" scenario, allowlist-based sanitization is almost always the correct answer. Blocklists and CSP-only solutions are common distractors designed to test whether you understand defense at the source.

Question 8

A server safely HTML-encodes a user's status message into a hidden <div>. Client-side code later reads the div's text and assigns it to another element using innerHTML. A reviewer claims the original server-side encoding makes the second operation safe.

Which statement best evaluates the reviewer's claim?

  1. The claim is correct because encoded data remains safe through all later browser operations.
  2. The claim is correct if the hidden div is not visible when the page initially loads.
  3. The claim is incorrect only when the status message exceeds the div's maximum length.
  4. The claim is incorrect because decoding and reinsertion into innerHTML creates a new sink. (correct answer)
Explanation: Whenever you see a question about Cross-Site Scripting (XSS), focus on the concept of sources and sinks. A source is where untrusted data enters your code; a sink is where that data is written into a dangerous context. The critical insight is that sanitization only protects you at the specific sink where it's applied — not at every future sink downstream. Here, the server correctly HTML-encodes the status message before writing it into the hidden <div>. That encoding neutralizes any malicious characters at that moment. However, when JavaScript later reads the div's .textContent (or .innerText), the browser automatically decodes the HTML entities back into their original characters — restoring any <script> tags or event handlers the attacker embedded. Assigning that decoded string to another element via innerHTML then interprets it as live HTML, completing the XSS attack. D is correct because the second innerHTML assignment is an entirely new, unsanitized sink, making the reviewer's claim false. A reflects a common and dangerous misconception — that encoding is a "one and done" protection that travels with the data. It doesn't. B introduces an irrelevant condition; the div's visibility has no bearing on whether JavaScript can read and reinsert its content. C confuses input length limits (a separate control) with injection vulnerability — message length is entirely unrelated to whether malicious HTML gets executed. Your study tip: always trace data through its full lifecycle in the browser. Ask "where does this data land next?" — because each new sink requires its own protection.

Question 9

A new administrative dashboard displays customer notes imported years ago from several legacy systems. The current customer portal validates newly submitted notes, so the team plans to render all database values directly because they are now considered internal data.

What is the most appropriate security recommendation?

  1. Render the notes directly because database storage establishes a trusted-data boundary.
  2. Validate only legacy notes at display time and render current notes without encoding.
  3. Encrypt stored notes and decrypt them immediately before inserting them into the page.
  4. Treat stored notes as untrusted and encode them for the dashboard's output context. (correct answer)
Explanation: When you see a question about rendering user-supplied or legacy data, think about the stored XSS threat model. The core principle is that data origin does not determine trust — where data ends up determines how you must handle it. Any value inserted into an HTML page can execute as code if it contains malicious markup, regardless of whether it came from a validated form or a decade-old database import. D is correct because legacy notes may have been imported from systems with little or no input validation, meaning they could contain embedded scripts or HTML that was never sanitized. Encoding output for the specific rendering context (HTML encoding for an HTML page, attribute encoding for attributes, etc.) neutralizes malicious payloads before the browser interprets them, regardless of how the data entered storage. A is dangerously wrong because database storage is not a trust boundary. Attackers who compromised a legacy system, or users who submitted malicious content before validation was added, may have already poisoned the data. Storing data does not sanitize it. B splits trust based on data age, which is arbitrary and fragile. Legacy data is actually more suspect, not less, because older systems typically had weaker validation. Rendering current notes without encoding still leaves an XSS vector open. C conflates confidentiality with integrity. Encryption protects data from unauthorized reading, but decrypting a malicious payload right before page insertion delivers it perfectly intact to the browser — encryption does nothing to prevent XSS. A reliable study rule: encode at output, every time, for every source. Trust is determined by context, never by storage location or data age.

Question 10

A registration page uses browser-side code to require an age from 18 through 120 and to limit a display name to 40 characters. The API accepts requests from the page and from mobile clients. A developer argues that repeating these checks in the API would be redundant.

Which approach best assigns responsibility for input validation?

  1. Keep browser validation for usability, but enforce authoritative constraints again at the API. (correct answer)
  2. Trust browser validation for web requests, but validate requests carrying a mobile user agent.
  3. Remove browser validation and perform all validation only after values reach the database.
  4. Retain browser checks and use HTML encoding on values before the API processes them.
Explanation: When you see a question about input validation in a system with multiple entry points, think about the trust boundary principle: validation performed on the client side can always be bypassed by an attacker, so the server must never rely on it as a security control. This is exactly why A is correct. Browser-side validation improves usability — it gives users instant feedback without a round trip to the server — but it is trivially bypassed using tools like Burp Suite, curl, or a custom mobile client. The API is the authoritative trust boundary, so it must independently enforce every constraint: the age range of 18–120, the 40-character display name limit, and anything else that matters for security or data integrity. The developer's "redundant" argument is a classic and dangerous misunderstanding. B is flawed because checking the User-Agent header for "mobile" provides zero real protection. Any attacker can spoof any user agent header in seconds. Trusting web requests because they came from a browser is the same mistake as trusting client-side validation. C moves validation to the database layer, which is too late. Malicious or malformed data may trigger errors, corrupt state, or exploit vulnerabilities before it ever reaches a constraint check. Defense-in-depth means catching bad input as early as possible on the server, not delegating it entirely downstream. D conflates two different controls. HTML encoding is an output-encoding technique used to prevent XSS when rendering data — it is not a substitute for input validation of business rules like age ranges or field lengths. Study tip: Remember "never trust the client" as a core security axiom. On exam questions, any answer that delegates security responsibility to the browser, a header, or the database should be an immediate red flag.