CAP-PC ENS study materials
CAP-PC ENS study resources

CAP-PC ENS practice questions

One question at a time. Build your CAP-PC ENS understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Web Application Security

A web application reflects user input into the HTML body without encoding. Which vulnerability class does this most directly enable?

  1. Server-side request forgery
  2. SQL injection
  3. Insecure direct object reference
  4. Cross-site scripting (XSS) Correct answer.

Explanation

Unencoded user input placed into an HTML response lets an attacker inject markup and script that execute in a victim's browser, which is the definition of cross-site scripting. SQL injection requires the input to reach a database query interpreter, and the other options involve object authorization or server-side requests rather than browser script execution.

Question 2Web Application Security

Which HTTP response header instructs modern browsers to block inline scripts unless they carry a matching nonce or hash?

  1. X-Content-Type-Options
  2. Strict-Transport-Security
  3. Referrer-Policy
  4. Content-Security-Policy Correct answer.

Explanation

Content-Security-Policy defines which script sources the browser may execute, and a policy without 'unsafe-inline' blocks inline scripts unless a nonce or hash matches. The other headers control HTTPS enforcement, MIME sniffing, and referrer leakage respectively.

Question 3Web Application Security

A session cookie is issued without the Secure attribute. What is the primary risk?

  1. The cookie can be read by JavaScript via document.cookie
  2. The cookie will never expire on the client
  3. The cookie can be transmitted over plaintext HTTP and intercepted Correct answer.
  4. The cookie will be shared across all subdomains automatically

Explanation

The Secure attribute restricts the browser to sending the cookie only over HTTPS, so omitting it allows the cookie to travel over unencrypted HTTP where a network attacker can capture it. JavaScript access is governed by HttpOnly, lifetime by Expires or Max-Age, and subdomain scope by the Domain attribute.

Question 4Web Application Security

An application builds a SQL query as "SELECT * FROM users WHERE name = '" + input + "'". Which mitigation most directly removes the injection risk?

  1. Escaping single quotes with a backslash
  2. Disabling verbose database error messages
  3. Restricting the input field to 20 characters
  4. Using parameterized queries with bound placeholders Correct answer.

Explanation

Parameterized queries separate SQL code from data so the database treats user input as a value, never as syntax. Manual escaping is error-prone and database-specific, length limits do not stop injection, and hiding errors only reduces information leakage.

Question 5Web Application Security

Which SameSite cookie value provides the strongest protection against cross-site request forgery while still allowing top-level navigation to the site?

  1. Unset
  2. None
  3. Lax
  4. Strict Correct answer.

Explanation

SameSite=Strict prevents the cookie from being sent on any cross-site request, including top-level navigations, giving the strongest CSRF protection. Lax still sends the cookie on top-level GET navigations, None disables the restriction, and an unset value falls back to browser defaults rather than providing a guarantee.

Question 6Web Application Security

What does the HttpOnly attribute on a session cookie prevent?

  1. Reading the cookie through client-side JavaScript Correct answer.
  2. Sending the cookie on cross-site requests
  3. Caching the cookie in a shared proxy
  4. Sending the cookie over an unencrypted connection

Explanation

HttpOnly removes the cookie from the document.cookie API, so injected scripts cannot directly steal it. Transport security is handled by Secure, cross-site sending by SameSite, and caching behavior by Cache-Control headers.

Question 7Web Application Security

Which practice best mitigates stored XSS in user-generated content that must display limited HTML formatting?

  1. Sanitizing the content with an allowlist-based HTML sanitizer on the server Correct answer.
  2. Blocking the string "<script" with a case-sensitive filter
  3. Storing the content base64-encoded in the database
  4. Relying on client-side JavaScript to strip tags before submission

Explanation

An allowlist sanitizer parses the markup and permits only known-safe tags and attributes, which resists encoding and mutation tricks. Naive string blocking is bypassable, client-side filtering can be skipped, and encoding changes storage form without neutralizing execution when decoded.

Question 8Web Application Security

A web application stores passwords using a fast general-purpose hash such as SHA-256 without a salt. Which weakness is most significant?

  1. The hash reveals the plaintext through reversible decoding
  2. Attackers can use precomputed rainbow tables and crack identical passwords in bulk Correct answer.
  3. The hash output is too long to store in the database
  4. The hash cannot be verified during login

Explanation

Unsalted fast hashes allow precomputed tables and let identical passwords produce identical digests, so one crack covers many accounts. Verification still works with any deterministic hash, length is not a practical storage problem, and cryptographic hashes are not reversible.

Question 9Web Application Security

A login form returns different messages for unknown usernames and wrong passwords. Which weakness does this introduce?

  1. Open redirect
  2. Username enumeration Correct answer.
  3. Session fixation
  4. Cross-site request forgery

Explanation

Distinct responses let an attacker determine which accounts exist, which is username enumeration and aids credential attacks. CSRF, session fixation, and open redirect concern request forgery, session handling, and URL redirection rather than account discovery.

Question 10Web Application Security

An application accepts a user-supplied "returnUrl" parameter and redirects to it after login without validation. Which attack does this enable?

  1. Open redirect used in phishing Correct answer.
  2. XML external entity injection
  3. HTTP response splitting
  4. Local file inclusion

Explanation

Redirecting to an unvalidated user-supplied URL lets attackers craft trusted-looking links that send victims to malicious sites, which is an open redirect. File inclusion, XXE, and response splitting involve local file access, XML parsers, and header injection respectively.

Question 11Web Application Security

Which control most directly defends an authenticated state-changing endpoint against CSRF when the API is consumed by a single-page application?

  1. Accepting only POST requests
  2. Relying on the Origin header being absent
  3. Setting the session cookie to SameSite=None
  4. Requiring a custom header with a per-session token that browsers do not send cross-origin by default Correct answer.

Explanation

Requiring a custom header carrying a token forces a CORS preflight and cannot be set by a simple cross-site form post, so forged requests fail. SameSite=None weakens protection, POST-only endpoints are still forgeable via forms, and treating a missing Origin as trusted is unsafe.

Question 12Web Application Security

A web server includes the file path from a query parameter in a file-read call without validation, and an attacker requests "../../etc/passwd". Which vulnerability is demonstrated?

  1. Cross-site scripting
  2. Server-side request forgery
  3. Path traversal Correct answer.
  4. Insecure deserialization

Explanation

Using unvalidated input in a filesystem path allows directory traversal sequences to escape the intended directory, which is path traversal. SSRF, XSS, and deserialization involve outbound requests, browser script, and object reconstruction respectively.

Question 13Web Application Security

Which statement correctly describes the difference between reflected and stored XSS?

  1. Reflected payloads are returned in the same response to the victim, while stored payloads persist on the server and execute for later visitors Correct answer.
  2. Reflected payloads persist in the database, while stored payloads appear only in the current response
  3. Reflected XSS requires the victim to be authenticated, while stored XSS never does
  4. Reflected XSS only affects the DOM, while stored XSS only affects server-rendered HTML

Explanation

Reflected XSS bounces the payload back in the immediate response, typically via a crafted link, whereas stored XSS is saved server-side and served to subsequent users. The other statements invert persistence or misattribute DOM and authentication characteristics.

Question 14Web Application Security

An application uses a strict Content-Security-Policy with per-response nonces but still reflects user input into an inline event handler attribute such as onclick. What is the most likely outcome?

  1. The injected handler may still execute because nonces do not authorize inline event handler attributes Correct answer.
  2. The browser will refuse to render the entire page
  3. The CSP will convert the handler into a safe external script
  4. The nonce automatically covers the injected handler and blocks it

Explanation

Nonces apply to script elements carrying the nonce, but inline event handler attributes remain blocked by default and are not made safe by the nonce; the real fix is output encoding and avoiding inline handlers. CSP does not rewrite handlers into external scripts, and it does not normally blank the whole page.

Question 15Web Application Security

Which mitigation best prevents an attacker from abusing a web application's image-fetch feature to reach internal metadata services?

  1. Enforce an allowlist of permitted destination hosts and block private address ranges Correct answer.
  2. Require the request to use HTTPS only
  3. Log the requested URL for later review
  4. Increase the request timeout for outbound fetches

Explanation

Server-side request forgery is mitigated by restricting destinations to known hosts and denying private, loopback, and link-local ranges so internal services cannot be reached. Timeouts, logging, and HTTPS enforcement do not stop the server from making the request.

Question 16Web Application Security

In a JWT-based authentication scheme, which configuration most directly allows an attacker to forge tokens?

  1. Including an expiration claim in the token
  2. Accepting the "none" algorithm or trusting the key specified in the token header Correct answer.
  3. Signing tokens with an asymmetric private key
  4. Storing the token in an HttpOnly cookie

Explanation

If the verifier honors an unsigned algorithm or attacker-supplied key material, the signature check becomes meaningless and tokens can be forged. Expiration, asymmetric signing, and HttpOnly storage are protective practices rather than forgery enablers.

Question 17Web Application Security

An API endpoint returns full user records when given an incremental numeric identifier, and any authenticated user can retrieve records belonging to others. Which flaw is present?

  1. Weak transport encryption
  2. Broken object-level authorization Correct answer.
  3. Insufficient logging
  4. Cross-site scripting

Explanation

The endpoint authenticates the caller but fails to verify that the caller owns the requested object, which is broken object-level authorization. The other options concern script injection, encryption strength, and monitoring rather than per-object access checks.

Question 18Web Application Security

A developer stores a user's role in a hidden form field so the client can display admin options. Why is this insecure?

  1. Hidden fields are stripped by all browsers before submission
  2. Hidden fields are encrypted by the browser and cannot be read
  3. Hidden fields bypass TLS and are sent in plaintext
  4. Clients can modify hidden fields, so the server must enforce authorization from trusted server-side state Correct answer.

Explanation

Hidden fields are client-controlled and can be edited with proxy tools or a browser console, so any authorization decision based on them is attacker-controlled. They are not encrypted, not stripped, and do not alter transport security.

Question 19Web Application Security

Which measure most effectively reduces the impact of a successful XSS attack on a session cookie?

  1. Storing additional user data in the cookie
  2. Setting the cookie Domain to the parent domain
  3. Disabling HTTPS for the cookie
  4. Marking the cookie HttpOnly and keeping session lifetime short Correct answer.

Explanation

HttpOnly prevents script from reading the cookie directly, and short lifetimes limit the window for abuse if it is compromised by other means. Broadening the domain, enlarging the cookie, and disabling HTTPS all increase exposure.

Question 20Web Application Security

A web application deserializes untrusted data from a cookie using a library that can instantiate arbitrary classes. Which risk is most significant?

  1. Cross-site request forgery via cookie replay
  2. Remote code execution through gadget chains during deserialization Correct answer.
  3. Clickjacking through framing
  4. Cache poisoning through header injection

Explanation

Unsafe deserialization of attacker-controlled data can trigger gadget chains that execute code on the server. CSRF, clickjacking, and cache poisoning involve forged requests, framing, and caching rather than object reconstruction.

Question 21Web Application Security

Which HTTP header combination best reduces clickjacking risk for a page that must not be framed by other origins?

  1. X-Frame-Options: ALLOW-FROM *
  2. Content-Security-Policy: frame-ancestors 'self' Correct answer.
  3. Access-Control-Allow-Origin: *
  4. Content-Type: text/html

Explanation

The frame-ancestors directive restricts which origins may embed the page, which is the modern clickjacking control. ALLOW-FROM with a wildcard is not a valid restriction, CORS headers govern data sharing, and Content-Type merely declares the media type.

Question 22Web Application Security

A team wants defense in depth against XSS. Which combination is most appropriate?

  1. Case-insensitive keyword blocking plus HTTPS only
  2. Client-side validation plus base64 encoding of output
  3. Context-aware output encoding plus a restrictive Content-Security-Policy Correct answer.
  4. Input length limits plus verbose error pages

Explanation

Encoding output for its exact context prevents injected markup from being interpreted, and a restrictive CSP limits damage if encoding fails. Length limits, error verbosity, client-side checks, and keyword blocking do not reliably neutralize injection.

Question 23Web Application Security

An application sets Access-Control-Allow-Origin by reflecting any incoming Origin value and also sets Access-Control-Allow-Credentials to true. What is the consequence?

  1. Any origin can read authenticated responses, defeating the same-origin policy for that endpoint Correct answer.
  2. Browsers will refuse all cross-origin requests to the endpoint
  3. Credentials are automatically stripped from all requests
  4. Only the application's own origin can read responses

Explanation

Reflecting arbitrary origins while allowing credentials lets any site issue credentialed requests and read the responses, which is a serious CORS misconfiguration. A fixed allowlist would restrict access, browsers do not block all requests, and credentials are not stripped automatically.

Question 24Web Application Security

A single-page application writes untrusted data into element.innerHTML based on the URL fragment. Which classification and fix are most accurate?

  1. DOM-based XSS; use safe sinks such as textContent or a sanitizer instead of innerHTML Correct answer.
  2. CSRF; add a SameSite=Strict cookie
  3. Stored XSS; enable database encryption
  4. Reflected XSS; add HttpOnly to the session cookie

Explanation

The payload never reaches the server and executes through a client-side sink, which is DOM-based XSS, and the remedy is to avoid dangerous sinks or sanitize input. Cookie flags, database encryption, and SameSite settings do not address client-side sink injection.

Question 25Web Application Security

A file upload feature validates the Content-Type header and the file extension but stores files in a web-accessible directory that executes scripts. Which additional control most reduces the risk of code execution?

  1. Require users to accept a terms-of-service page before uploading
  2. Store uploads outside the web root and serve them through a handler that forces a safe content type Correct answer.
  3. Increase the maximum upload size
  4. Rename files with random UUIDs while keeping script execution enabled

Explanation

Storing uploads outside the document root and serving them with a non-executable content type prevents the server from running uploaded code, even if validation is bypassed. Size limits, random names in an executable directory, and policy acknowledgements do not stop execution.

Question 26Web Application Security

Which cookie attribute instructs the browser to send the cookie only over HTTPS connections, protecting session identifiers from passive network eavesdroppers?

  1. SameSite
  2. Secure Correct answer.
  3. Path
  4. Domain

Explanation

The Secure attribute tells the browser to transmit the cookie only over encrypted HTTPS channels, so a passive attacker sniffing plaintext HTTP cannot capture the session token. It does not itself prevent script access or cross-site sending, so it is normally combined with HttpOnly and SameSite.

Question 27Web Application Security

A web application concatenates a username from a query string directly into a SQL statement executed by the database driver. Which vulnerability class does this most directly create?

  1. Cross-site scripting
  2. Insecure deserialization
  3. SQL injection Correct answer.
  4. Open redirect

Explanation

Building SQL by string concatenation lets attacker-controlled input alter the query structure, which is the definition of SQL injection. Parameterized queries or prepared statements keep data separate from code and eliminate the flaw.

Question 28Web Application Security

Which HTTP response header directs browsers to upgrade future requests to HTTPS for a specified period and optionally include subdomains?

  1. X-Content-Type-Options
  2. Referrer-Policy
  3. Strict-Transport-Security Correct answer.
  4. Content-Security-Policy

Explanation

Strict-Transport-Security (HSTS) instructs the browser to use HTTPS for the host for the declared max-age window, and includeSubDomains extends that to subdomains. It prevents protocol-downgrade attacks after the policy has been received once.

Question 29Web Application Security

An application renders a page that must never be embedded in a frame by another origin. Which response header most directly enforces this at the browser?

  1. Access-Control-Allow-Origin: *
  2. Cache-Control: no-store
  3. X-Frame-Options: DENY Correct answer.
  4. Content-Security-Policy: default-src 'self'

Explanation

X-Frame-Options: DENY tells the browser to refuse to render the page inside any frame, which blocks classic clickjacking. The modern equivalent is the CSP frame-ancestors directive, but the X-Frame-Options header is the direct legacy control.

Question 30Web Application Security

Which practice best protects against credential stuffing against a login endpoint?

  1. Returning the same generic error for all failed logins
  2. Storing passwords with reversible encryption instead of hashing
  3. Requiring users to change their password every 30 days
  4. Enforcing rate limiting and anomaly detection on repeated failed logins Correct answer.

Explanation

Credential stuffing replays leaked username/password pairs at scale, so throttling, lockouts, and anomaly detection on failed authentication are the primary defenses. Generic error messages reduce enumeration but do not slow automated guessing.

Question 31Web Application Security

Which input validation approach is most robust for a field that must accept only a numeric account identifier?

  1. Allowlisting with a strict pattern such as ^[0-9]{1,10}$ and enforcing it server-side Correct answer.
  2. Rejecting requests that contain the word "select"
  3. Relying on the client-side JavaScript validation only
  4. Escaping special characters in the identifier before storing it

Explanation

Allowlisting restricts input to a known-safe character set and length, and enforcing it on the server prevents bypass of client controls. Escaping is a context-specific output defense, not a substitute for validating the input shape.

Question 32Web Application Security

What is the primary purpose of the SameSite=Strict attribute on a session cookie?

  1. To encrypt the cookie value in transit
  2. To prevent the cookie from being sent on cross-site requests Correct answer.
  3. To limit the cookie to a single URL path
  4. To hide the cookie from JavaScript

Explanation

SameSite=Strict stops the browser from attaching the cookie to requests initiated by other sites, which mitigates cross-site request forgery. It is a scope control on when the cookie is sent, not a confidentiality or integrity mechanism.

Question 33Web Application Security

Which encoding should be applied to untrusted data inserted into an HTML element's text content on the server side?

  1. JavaScript hex escaping
  2. Base64 encoding
  3. URL encoding
  4. HTML entity encoding Correct answer.

Explanation

HTML entity encoding converts characters such as < and & into entities so the browser treats them as text rather than markup. The correct encoding depends on the output context, and for HTML body text that context is HTML.

Question 34Web Application Security

An application stores password hashes using a single round of a fast hash. Which change most directly increases resistance to offline cracking if the database is stolen?

  1. Switching to a slower, memory-hard password hashing function Correct answer.
  2. Hashing the password twice with the same algorithm
  3. Encrypting the hash column with a static key
  4. Adding a random salt per password

Explanation

Memory-hard, deliberately slow functions such as Argon2id or bcrypt raise the cost of each guess, which is the main lever against offline cracking. Salting is still required, but it only defeats precomputation and identical-password correlation, not brute force of individual hashes.

Question 35Web Application Security

A page uses a Content-Security-Policy of default-src 'self' and includes an inline event handler attribute such as onclick="doThing()". What happens in a browser that enforces the policy?

  1. The handler is blocked because inline script is not allowed Correct answer.
  2. The handler executes but logs a console warning
  3. The handler executes because it is same-origin
  4. The handler executes only after a user gesture

Explanation

A policy without 'unsafe-inline' or a matching hash/nonce blocks inline scripts, including inline event handler attributes. This is why inline handlers must be replaced with addEventListener and external scripts.

Question 36Web Application Security

Which control most directly prevents an attacker from reading another user's invoice by changing the invoice ID in a URL?

  1. Rate limiting per IP address
  2. A CAPTCHA on the invoice page
  3. Obfuscating invoice IDs with a reversible encoding
  4. Object-level authorization checks on each request Correct answer.

Explanation

Broken object-level authorization (IDOR) is fixed by verifying on the server that the authenticated principal owns or may access the requested object. Hiding or encoding identifiers does not replace that check.

Question 37Web Application Security

Which statement about Subresource Integrity (SRI) on a script tag is correct?

  1. It prevents the script from accessing cookies
  2. It verifies that a fetched script matches a declared cryptographic hash Correct answer.
  3. It encrypts the script in transit between CDN and browser
  4. It restricts the script to same-origin execution

Explanation

The integrity attribute contains a hash of the expected resource, and the browser refuses to execute the resource if the fetched bytes do not match. This protects against a compromised or malicious third-party CDN serving altered code.

Question 38Web Application Security

A developer wants to prevent an attacker from reusing a stolen session identifier after the user logs in. Which practice addresses this most directly?

  1. Extending the session timeout to 24 hours
  2. Setting the cookie Path to /
  3. Storing the session identifier in localStorage
  4. Rotating the session identifier at authentication Correct answer.

Explanation

Session fixation is defeated by issuing a fresh session identifier when privileges change, such as at login, and invalidating the old one. This ensures a pre-authentication identifier known to an attacker becomes useless.

Question 39Web Application Security

Which approach best mitigates server-side request forgery in a feature that fetches a user-supplied URL?

  1. Logging every fetched URL for later review
  2. Blocking URLs that contain the string "localhost"
  3. Resolving the hostname and blocking private, loopback, and link-local address ranges Correct answer.
  4. Requiring the URL to use HTTP instead of HTTPS

Explanation

SSRF defenses must validate the resolved destination address, not just the textual hostname, because DNS can resolve to internal ranges or be rebound. Blocking private, loopback, and link-local ranges after resolution addresses the core risk.

Question 40Web Application Security

Which XML parser configuration most directly prevents XML External Entity attacks?

  1. Enabling schema validation against a local XSD
  2. Setting a maximum document size
  3. Parsing the document in a separate thread
  4. Disabling external entity and DTD processing Correct answer.

Explanation

XXE arises when the parser resolves external entities declared in a DTD, allowing file disclosure or SSRF. Disabling DTDs and external entity resolution removes the capability entirely.

Question 41Web Application Security

A team sets Access-Control-Allow-Credentials: true. Which accompanying configuration is required for cross-origin credentialed requests to succeed?

  1. A Content-Type of text/plain on preflight responses
  2. A longer Access-Control-Max-Age value
  3. The Vary: Cookie header on every response
  4. A specific allowed origin rather than the wildcard Correct answer.

Explanation

Browsers reject credentialed cross-origin requests when Access-Control-Allow-Origin is the wildcard, so the server must echo a specific trusted origin. Combining credentials with a reflected arbitrary origin would let any site read authenticated responses.

Question 42Web Application Security

Which of the following best describes a DOM-based cross-site scripting vulnerability?

  1. The server reflects input into the HTML response
  2. The database stores attacker input that is later rendered
  3. Client-side JavaScript writes attacker-controlled data into a dangerous sink Correct answer.
  4. The attacker injects script into a template compiled on the server

Explanation

DOM-based XSS occurs entirely in the browser when script reads a source such as location.hash and passes it to a sink like innerHTML without safe handling. The malicious data may never reach the server, so server-side filtering alone cannot detect it.

Question 43Web Application Security

An application must display user-supplied text inside an HTML attribute value. Which encoding is appropriate for that context?

  1. Base64 encoding of the value
  2. URL encoding of the entire attribute
  3. No encoding, because attribute values are always safe
  4. HTML attribute encoding that escapes quotes and metacharacters Correct answer.

Explanation

Attribute context requires encoding that neutralizes quote characters and other metacharacters so the value cannot break out of the attribute. Unquoted or improperly encoded attributes allow event handler injection.

Question 44Web Application Security

Which practice best limits the damage if an attacker achieves remote code execution in a container running the web application?

  1. Storing database credentials in environment variables of the image
  2. Enabling verbose stack traces in production responses
  3. Running the process as a non-root user with a read-only filesystem and minimal capabilities Correct answer.
  4. Mounting the Docker socket into the container for convenience

Explanation

Least privilege inside the container reduces what the attacker can do after code execution, since a non-root user, read-only filesystem, and dropped capabilities restrict persistence and lateral movement. Container hardening complements, but does not replace, fixing the underlying flaw.

Question 45Web Application Security

Which mechanism allows a site to instruct browsers to report CSP violations to an endpoint for monitoring?

  1. The Access-Control-Allow-Origin header
  2. The Content-Encoding header
  3. The report-uri or report-to directive in the policy Correct answer.
  4. The X-XSS-Protection header

Explanation

CSP supports violation reporting through report-uri, and the newer report-to directive integrates with the Reporting API. Reports help teams detect attempted injections and misconfigurations without blocking legitimate traffic.

Question 46Web Application Security

A REST API authenticates users with bearer tokens and also accepts a token in a URL query parameter. Why is placing the token in the URL risky?

  1. The server cannot parse query parameters reliably
  2. Query parameters are not encrypted by TLS
  3. Tokens in URLs bypass authentication entirely
  4. URLs are logged in proxies, browsers, and server logs, exposing the token Correct answer.

Explanation

URLs are commonly recorded in access logs, browser history, and intermediary caches, so a token in the query string leaks to parties that never see the request body. Authorization headers keep the credential out of those logs.

Question 47Web Application Security

Which of the following best explains why client-side authorization checks in a single-page application are insufficient?

  1. The API cannot determine which user is authenticated
  2. Browsers refuse to execute authorization logic in JavaScript
  3. Client-side checks are always slower than server checks
  4. Attackers can call the API directly, bypassing the client code entirely Correct answer.

Explanation

Any check performed in the browser can be skipped by sending crafted requests straight to the API, so authorization must be enforced server-side for every request. Client checks are a usability aid, not a security boundary.

Question 48Web Application Security

An application uses a strict CSP with nonces but generates the same nonce for every response over a long period. What is the primary risk?

  1. An attacker who learns the reusable nonce can inject a script that the policy will allow Correct answer.
  2. The nonce will be exposed through the Referer header
  3. The nonce will cause the page to fail to load entirely
  4. The nonce will disable HTTPS enforcement

Explanation

A CSP nonce must be unpredictable and unique per response; a predictable or reused value lets an attacker craft an injected script tag carrying the accepted nonce. Fresh, cryptographically random nonces per response preserve the protection.

Question 49Web Application Security

A web application reflects a JSON value into a script block as var data = {json}; and escapes only < and >. Which attack is most likely to succeed?

  1. Injecting a SQL payload through the JSON value
  2. Exploiting a race condition in the JSON parser
  3. Triggering an open redirect via the JSON field
  4. Breaking out of the script context using a crafted string that closes the script element or injects a new one Correct answer.

Explanation

Escaping only angle brackets leaves quotes and other characters intact, and the HTML parser terminates a script element on the literal sequence </script regardless of JavaScript string state. Safe serialization plus context-aware encoding, or placing data in a JSON endpoint fetched separately, avoids the flaw.

Question 50Web Application Security

An application validates uploaded images by checking the file extension and the Content-Type header only. Which additional server-side control most directly addresses the residual risk of a malicious file being served?

  1. Verifying file content signatures and serving uploads from a separate origin with a restrictive Content-Type and Content-Disposition Correct answer.
  2. Limiting uploads to files smaller than 1 MB
  3. Renaming the uploaded file to a random UUID
  4. Requiring users to accept a terms-of-service checkbox

Explanation

Extension and header checks are attacker-controlled, so content must be validated and stored files must be served in a way that prevents browser interpretation, such as a separate origin plus nosniff and attachment disposition. This blocks stored XSS and similar payload delivery via uploads.