Web Security MCQ 60 Tests With Answers (2026)

Web Security MCQ practice questions are essential for preparing for competitive exams, certifications (CompTIA Security+, CISSP), and technical interviews. This comprehensive MCQ platform provides 60 carefully curated practice questions covering web application security fundamentals, key threats, and defensive strategies.
These questions are organized into three progressive difficulty levels of 20 questions each: Basics (covering foundational terminology and core definitions), Concepts (covering intermediate protocols, threat mechanics, and architectural trade-offs), and Advanced (covering scenario-based analysis, advanced compliance, and enterprise architectures). Each question includes a verified, in-depth explanation to reinforce learning.
Practice in Study Mode to reveal answers and detailed explanations instantly, or use Exam Mode for timed testing and real-time scoring to simulate CompTIA Security+ or university exam conditions. The interactive engine tracks your progress and identifies knowledge gaps across client-side defenses, server-side code execution, and backend API integrations.
Contents
- 1.Basics (20 Questions)HTTP vs HTTPS Β· cookies flags Β· password hashing Β· SSL/TLS Β· status codes Β· DoS
- 2.Concepts (20 Questions)Same-Origin Policy Β· XSS Β· SQLi Β· CSRF Β· CORS Β· CSP Β· WAF Β· clickjacking
- 3.Advanced (20 Questions)XXE Β· SSRF Β· JWT vulnerabilities Β· HTTP Request Smuggling Β· OAuth 2.0 Β· DOM XSS Β· prototype pollution
- 4.Conclusionsummary Β· next steps Β· study tips
- 5.Key Takeawaysquick-fire bullet recap of essential facts
- 6.Quick Review Summaryconcept Β· definition Β· key fact table
- 7.FAQcommon questions answered
Web Security β Basics
1Which of the following best describes the primary function of a Web Cookie?
CorrectD: A small piece of data stored by the user's web browser to track sessions or preferences
A web cookie is a small piece of data (key-value pair) that a web server sends to the user's browser, which stores it locally and sends it back with subsequent requests to the same domain. Cookies are used to maintain session state (session tokens), track user preferences, store login status, and enable shopping carts β all because HTTP is inherently stateless and has no memory of previous requests.
IncorrectD: A small piece of data stored by the user's web browser to track sessions or preferences
A web cookie is a small piece of data (key-value pair) that a web server sends to the user's browser, which stores it locally and sends it back with subsequent requests to the same domain. Cookies are used to maintain session state (session tokens), track user preferences, store login status, and enable shopping carts β all because HTTP is inherently stateless and has no memory of previous requests.
2What is the fundamental difference between HTTP and HTTPS?
CorrectB: HTTPS encrypts the data transmitted between the client and server using TLS/SSL
HTTPS (HTTP Secure) is HTTP transported over a TLS (Transport Layer Security) tunnel. TLS encrypts all data in transit between the browser and server, preventing eavesdropping and Man-in-the-Middle attacks. HTTP uses port 80 by default; HTTPS uses port 443. Without HTTPS, passwords, session tokens, and personal data travel as cleartext across the network, visible to anyone with a packet sniffer.
IncorrectB: HTTPS encrypts the data transmitted between the client and server using TLS/SSL
HTTPS (HTTP Secure) is HTTP transported over a TLS (Transport Layer Security) tunnel. TLS encrypts all data in transit between the browser and server, preventing eavesdropping and Man-in-the-Middle attacks. HTTP uses port 80 by default; HTTPS uses port 443. Without HTTPS, passwords, session tokens, and personal data travel as cleartext across the network, visible to anyone with a packet sniffer.
3What does a "404 Not Found" HTTP status code indicate?
CorrectB: The specific web page or resource requested does not exist on the server
HTTP 404 Not Found is a client-side error indicating the server successfully received the request but cannot find the requested resource at that URI. Key HTTP status code families: 1xx (Informational), 2xx (Success β e.g., 200 OK), 3xx (Redirection β e.g., 301 Moved), 4xx (Client Errors β e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found), 5xx (Server Errors β e.g., 500 Internal Server Error).
IncorrectB: The specific web page or resource requested does not exist on the server
HTTP 404 Not Found is a client-side error indicating the server successfully received the request but cannot find the requested resource at that URI. Key HTTP status code families: 1xx (Informational), 2xx (Success β e.g., 200 OK), 3xx (Redirection β e.g., 301 Moved), 4xx (Client Errors β e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found), 5xx (Server Errors β e.g., 500 Internal Server Error).
4In the context of web security, what is "Phishing"?
CorrectA: The practice of creating deceptive emails or websites to trick users into revealing sensitive information
Phishing is a social engineering attack where an attacker crafts deceptive emails, SMS (smishing), or fake websites impersonating legitimate organizations to trick users into revealing credentials, financial data, or personally identifiable information (PII). Phishing is the most common entry point for data breaches. Technical controls include email authentication (SPF, DKIM, DMARC), browser phishing filters, and security awareness training.
IncorrectA: The practice of creating deceptive emails or websites to trick users into revealing sensitive information
Phishing is a social engineering attack where an attacker crafts deceptive emails, SMS (smishing), or fake websites impersonating legitimate organizations to trick users into revealing credentials, financial data, or personally identifiable information (PII). Phishing is the most common entry point for data breaches. Technical controls include email authentication (SPF, DKIM, DMARC), browser phishing filters, and security awareness training.
5What is the primary purpose of a Digital Certificate on a website?
CorrectC: To cryptographically verify the identity of the website and enable secure TLS/SSL connections
A Digital Certificate (X.509 TLS/SSL certificate) is issued by a trusted Certificate Authority (CA) and cryptographically binds a domain name to a public key. This allows browsers to: (1) verify the website is genuinely who it claims to be (authentication), and (2) use the public key to establish an encrypted TLS session (enabling HTTPS). Without certificate validation, browsers cannot distinguish a legitimate site from an impersonator.
IncorrectC: To cryptographically verify the identity of the website and enable secure TLS/SSL connections
A Digital Certificate (X.509 TLS/SSL certificate) is issued by a trusted Certificate Authority (CA) and cryptographically binds a domain name to a public key. This allows browsers to: (1) verify the website is genuinely who it claims to be (authentication), and (2) use the public key to establish an encrypted TLS session (enabling HTTPS). Without certificate validation, browsers cannot distinguish a legitimate site from an impersonator.
6Which of the following represents the safest way for a web application to store user passwords in its database?
CorrectA: Hashed and salted using a strong algorithm like Argon2 or bcrypt
Passwords must be hashed with a strong, deliberately slow, one-way password hashing function β not encryption (reversible) or general-purpose hashes (fast, brute-forceable). Best practices: Argon2id (winner of the Password Hashing Competition, recommended by OWASP), bcrypt, or scrypt. Salting adds a unique random value per password before hashing, defeating rainbow table attacks. Base64 is encoding (not encryption) and is trivially reversible.
IncorrectA: Hashed and salted using a strong algorithm like Argon2 or bcrypt
Passwords must be hashed with a strong, deliberately slow, one-way password hashing function β not encryption (reversible) or general-purpose hashes (fast, brute-forceable). Best practices: Argon2id (winner of the Password Hashing Competition, recommended by OWASP), bcrypt, or scrypt. Salting adds a unique random value per password before hashing, defeating rainbow table attacks. Base64 is encoding (not encryption) and is trivially reversible.
7What does the acronym "URL" stand for?
CorrectC: Uniform Resource Locator
URL stands for Uniform Resource Locator β the complete address used to locate a resource on the internet. A URL has distinct parts: scheme (https://), subdomain (www.), domain (example), TLD (.com), path (/page), query string (?key=value), and fragment (#section). URL encoding replaces special characters with % followed by their hex value (e.g., space = %20), which is critical to understand for detecting certain injection attacks.
IncorrectC: Uniform Resource Locator
URL stands for Uniform Resource Locator β the complete address used to locate a resource on the internet. A URL has distinct parts: scheme (https://), subdomain (www.), domain (example), TLD (.com), path (/page), query string (?key=value), and fragment (#section). URL encoding replaces special characters with % followed by their hex value (e.g., space = %20), which is critical to understand for detecting certain injection attacks.
8What is the primary security benefit of using a Password Manager?
CorrectA: It allows users to generate and store unique, highly complex passwords for every website
The greatest password security risk is password reuse β if one site is breached, attackers use those credentials on other sites (credential stuffing). A password manager solves this by generating and securely storing unique, high-entropy passwords (e.g., 24+ random characters) for every site, so users only need to remember one master password. This eliminates both password reuse and weak, memorable passwords.
IncorrectA: It allows users to generate and store unique, highly complex passwords for every website
The greatest password security risk is password reuse β if one site is breached, attackers use those credentials on other sites (credential stuffing). A password manager solves this by generating and securely storing unique, high-entropy passwords (e.g., 24+ random characters) for every site, so users only need to remember one master password. This eliminates both password reuse and weak, memorable passwords.
9What is a CAPTCHA primarily designed to do?
CorrectD: Distinguish human users from automated bots to prevent spam and abuse
CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a challenge-response test designed to ensure a response is generated by a human, not an automated bot. CAPTCHAs protect web forms from automated abuse: spam submissions, account creation bots, credential stuffing attacks, and automated scraping. Modern versions (Google reCAPTCHA v3) use behavioral analysis instead of visual puzzles.
IncorrectD: Distinguish human users from automated bots to prevent spam and abuse
CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a challenge-response test designed to ensure a response is generated by a human, not an automated bot. CAPTCHAs protect web forms from automated abuse: spam submissions, account creation bots, credential stuffing attacks, and automated scraping. Modern versions (Google reCAPTCHA v3) use behavioral analysis instead of visual puzzles.
10Which standard network port is typically used for secure HTTPS web traffic?
CorrectC: Port 443
Port 443 is the standard IANA-assigned port for HTTPS (HTTP over TLS). Key web ports: Port 80 (HTTP), Port 443 (HTTPS), Port 21 (FTP), Port 22 (SSH), Port 25 (SMTP), Port 53 (DNS), Port 3306 (MySQL). In security contexts, knowing which ports serve what protocols is essential for firewall rule design, port scanning interpretation, and correctly diagnosing service exposure.
IncorrectC: Port 443
Port 443 is the standard IANA-assigned port for HTTPS (HTTP over TLS). Key web ports: Port 80 (HTTP), Port 443 (HTTPS), Port 21 (FTP), Port 22 (SSH), Port 25 (SMTP), Port 53 (DNS), Port 3306 (MySQL). In security contexts, knowing which ports serve what protocols is essential for firewall rule design, port scanning interpretation, and correctly diagnosing service exposure.
11What does Multi-Factor Authentication (MFA) add to a web login process?
CorrectB: It requires two or more independent forms of verification (e.g., password + SMS code) to prove identity
MFA (Multi-Factor Authentication) requires users to provide two or more independent authentication factors from different categories: something you know (password/PIN), something you have (OTP app, hardware key, SMS code), or something you are (biometric). Even if an attacker steals a password, they cannot authenticate without the second factor. TOTP-based authenticator apps (Google Authenticator, Authy) are significantly more secure than SMS-based MFA.
IncorrectB: It requires two or more independent forms of verification (e.g., password + SMS code) to prove identity
MFA (Multi-Factor Authentication) requires users to provide two or more independent authentication factors from different categories: something you know (password/PIN), something you have (OTP app, hardware key, SMS code), or something you are (biometric). Even if an attacker steals a password, they cannot authenticate without the second factor. TOTP-based authenticator apps (Google Authenticator, Authy) are significantly more secure than SMS-based MFA.
12When you clear your web browser's "Cache", what are you actually removing?
CorrectA: Temporary local copies of website images, scripts, and HTML used to speed up load times
The browser cache stores temporary local copies of web resources (HTML, CSS, JavaScript, images) from previously visited websites. On subsequent visits, the browser serves these from the local cache rather than re-downloading them, speeding up load times. From a security perspective, sensitive data inadvertently cached (e.g., on shared computers) can be exposed. Cache-Control headers (no-store, no-cache) instruct browsers not to cache sensitive responses.
IncorrectA: Temporary local copies of website images, scripts, and HTML used to speed up load times
The browser cache stores temporary local copies of web resources (HTML, CSS, JavaScript, images) from previously visited websites. On subsequent visits, the browser serves these from the local cache rather than re-downloading them, speeding up load times. From a security perspective, sensitive data inadvertently cached (e.g., on shared computers) can be exposed. Cache-Control headers (no-store, no-cache) instruct browsers not to cache sensitive responses.
13What is an IP address in the context of the World Wide Web?
CorrectD: A unique numerical identifier assigned to every device connected to the internet
An IP (Internet Protocol) address is a unique numerical identifier assigned to each device on a network. IPv4 addresses are 32-bit numbers in dotted-decimal notation (e.g., 192.168.1.1); IPv6 addresses are 128-bit in hexadecimal (e.g., 2001:0db8::1). In web security, IP addresses are used for access control, geolocation blocking, rate limiting, threat intelligence lookups, and are critical artifacts in log analysis and incident response.
IncorrectD: A unique numerical identifier assigned to every device connected to the internet
An IP (Internet Protocol) address is a unique numerical identifier assigned to each device on a network. IPv4 addresses are 32-bit numbers in dotted-decimal notation (e.g., 192.168.1.1); IPv6 addresses are 128-bit in hexadecimal (e.g., 2001:0db8::1). In web security, IP addresses are used for access control, geolocation blocking, rate limiting, threat intelligence lookups, and are critical artifacts in log analysis and incident response.
14What does "Incognito" or "Private Browsing" mode actually do?
CorrectA: It prevents the browser from saving your local search history, cookies, and form data after the session ends
Private/Incognito mode prevents the browser from persisting browsing history, cookies, form data, and cached files to disk after the session ends. It does NOT make you anonymous: your ISP still sees your traffic, websites still log your IP address, and network administrators can still monitor your activity. It is most useful for preventing local browsing history exposure on shared devices or separating session cookies between accounts.
IncorrectA: It prevents the browser from saving your local search history, cookies, and form data after the session ends
Private/Incognito mode prevents the browser from persisting browsing history, cookies, form data, and cached files to disk after the session ends. It does NOT make you anonymous: your ISP still sees your traffic, websites still log your IP address, and network administrators can still monitor your activity. It is most useful for preventing local browsing history exposure on shared devices or separating session cookies between accounts.
15What is the purpose of a VPN (Virtual Private Network) while browsing the web?
CorrectD: To create a secure, encrypted tunnel between the user's device and a remote server, masking the user's IP and traffic
A VPN routes all network traffic through an encrypted tunnel to a remote VPN server, which then forwards requests on the user's behalf. This masks the user's true IP address (websites see the VPN server's IP), prevents ISPs and local network monitors from seeing traffic content, and protects against eavesdropping on insecure Wi-Fi. VPNs do not provide anonymity (the VPN provider sees all traffic) and do not prevent tracking via cookies or browser fingerprinting.
IncorrectD: To create a secure, encrypted tunnel between the user's device and a remote server, masking the user's IP and traffic
A VPN routes all network traffic through an encrypted tunnel to a remote VPN server, which then forwards requests on the user's behalf. This masks the user's true IP address (websites see the VPN server's IP), prevents ISPs and local network monitors from seeing traffic content, and protects against eavesdropping on insecure Wi-Fi. VPNs do not provide anonymity (the VPN provider sees all traffic) and do not prevent tracking via cookies or browser fingerprinting.
16Which HTTP status code indicates a successful client request (i.e., "OK")?
CorrectD: 200
HTTP 200 OK is the standard success response indicating the request was received, understood, and processed successfully. Security-relevant codes: 200 (OK), 301/302 (Redirect β check for open redirects), 400 (Bad Request β malformed input), 401 (Unauthorized β authentication required), 403 (Forbidden β authenticated but not authorized), 404 (Not Found), 429 (Too Many Requests β rate limiting), 500 (Internal Server Error β potential info disclosure in stack traces).
IncorrectD: 200
HTTP 200 OK is the standard success response indicating the request was received, understood, and processed successfully. Security-relevant codes: 200 (OK), 301/302 (Redirect β check for open redirects), 400 (Bad Request β malformed input), 401 (Unauthorized β authentication required), 403 (Forbidden β authenticated but not authorized), 404 (Not Found), 429 (Too Many Requests β rate limiting), 500 (Internal Server Error β potential info disclosure in stack traces).
17What is malware in the context of a web browser?
CorrectA: Malicious software or scripts designed to disrupt, damage, or gain unauthorized access to a system
Malware (malicious software) delivered via web browsers includes: drive-by downloads (exploiting browser vulnerabilities to silently install software), malicious browser extensions (keyloggers, adware), JavaScript-based cryptominers, formjackers (scripts that steal form data), and malvertising (malicious code delivered via advertising networks). Browser security features like sandboxing, site isolation, and Content Security Policy help mitigate browser-based malware delivery.
IncorrectA: Malicious software or scripts designed to disrupt, damage, or gain unauthorized access to a system
Malware (malicious software) delivered via web browsers includes: drive-by downloads (exploiting browser vulnerabilities to silently install software), malicious browser extensions (keyloggers, adware), JavaScript-based cryptominers, formjackers (scripts that steal form data), and malvertising (malicious code delivered via advertising networks). Browser security features like sandboxing, site isolation, and Content Security Policy help mitigate browser-based malware delivery.
18What does "SSL" stand for in web security?
CorrectB: Secure Sockets Layer
SSL stands for Secure Sockets Layer β an older cryptographic protocol developed by Netscape to secure internet communications. SSL has been fully deprecated due to critical vulnerabilities (POODLE, BEAST, DROWN). Its successor is TLS (Transport Layer Security), currently at TLS 1.3. Despite being deprecated, "SSL" is still colloquially used when people mean TLS. All modern HTTPS connections use TLS 1.2 or 1.3 β never SSL 2.0 or 3.0.
IncorrectB: Secure Sockets Layer
SSL stands for Secure Sockets Layer β an older cryptographic protocol developed by Netscape to secure internet communications. SSL has been fully deprecated due to critical vulnerabilities (POODLE, BEAST, DROWN). Its successor is TLS (Transport Layer Security), currently at TLS 1.3. Despite being deprecated, "SSL" is still colloquially used when people mean TLS. All modern HTTPS connections use TLS 1.2 or 1.3 β never SSL 2.0 or 3.0.
19What is a Denial of Service (DoS) attack against a website?
CorrectC: Overwhelming the web server with excessive traffic or requests so it cannot respond to legitimate users
A DoS (Denial of Service) attack floods a web server with more requests than it can handle, exhausting CPU, memory, bandwidth, or connection limits β making the service unavailable to legitimate users. A DDoS (Distributed DoS) attack uses a botnet of thousands of compromised machines to amplify the attack. Mitigations include rate limiting, CAPTCHAs, IP blacklisting, CDN-based traffic scrubbing, and BGP blackholing for large-scale attacks.
IncorrectC: Overwhelming the web server with excessive traffic or requests so it cannot respond to legitimate users
A DoS (Denial of Service) attack floods a web server with more requests than it can handle, exhausting CPU, memory, bandwidth, or connection limits β making the service unavailable to legitimate users. A DDoS (Distributed DoS) attack uses a botnet of thousands of compromised machines to amplify the attack. Mitigations include rate limiting, CAPTCHAs, IP blacklisting, CDN-based traffic scrubbing, and BGP blackholing for large-scale attacks.
20Which entity translates human-readable web addresses (like www.example.com) into IP addresses?
CorrectB: DNS (Domain Name System)
DNS (Domain Name System) is the internet's distributed "phone book" that translates human-readable domain names into IP addresses. Without DNS, users would need to remember IP addresses for every website. DNS is critical for web security: DNS poisoning/spoofing attacks manipulate DNS responses to redirect users to malicious sites, DNSSEC cryptographically signs DNS records to prevent poisoning, and DNS filtering is used to block malicious domains at the network level.
IncorrectB: DNS (Domain Name System)
DNS (Domain Name System) is the internet's distributed "phone book" that translates human-readable domain names into IP addresses. Without DNS, users would need to remember IP addresses for every website. DNS is critical for web security: DNS poisoning/spoofing attacks manipulate DNS responses to redirect users to malicious sites, DNSSEC cryptographically signs DNS records to prevent poisoning, and DNS filtering is used to block malicious domains at the network level.
Web Security β Concepts
1What is the mechanism behind a Cross-Site Scripting (XSS) attack?
CorrectA: An attacker injects malicious client-side executable scripts into trusted web pages viewed by other users
XSS (Cross-Site Scripting) exploits a web application's failure to properly sanitize user-supplied content before including it in HTML output. When a victim's browser renders the page, it executes the injected JavaScript in the context of the trusted domain β allowing the attacker to steal session cookies (document.cookie), perform actions on behalf of the user, redirect to phishing pages, or log keystrokes. XSS is prevented by output encoding (HTML entity encoding), Content Security Policy, and input validation.
IncorrectA: An attacker injects malicious client-side executable scripts into trusted web pages viewed by other users
XSS (Cross-Site Scripting) exploits a web application's failure to properly sanitize user-supplied content before including it in HTML output. When a victim's browser renders the page, it executes the injected JavaScript in the context of the trusted domain β allowing the attacker to steal session cookies (document.cookie), perform actions on behalf of the user, redirect to phishing pages, or log keystrokes. XSS is prevented by output encoding (HTML entity encoding), Content Security Policy, and input validation.
2What does the "Same-Origin Policy" (SOP) dictate in a web browser?
CorrectA: It restricts how a document or script loaded from one origin can interact with a resource from another origin
The Same-Origin Policy (SOP) is a critical browser security mechanism that prevents JavaScript from making cross-origin requests. Two URLs share the same origin only if all three components match: protocol (http vs https), hostname (example.com), and port (80 vs 443). SOP prevents a malicious site from reading your bank's response via JavaScript. CORS is the controlled mechanism to relax SOP when cross-origin access is genuinely needed.
IncorrectA: It restricts how a document or script loaded from one origin can interact with a resource from another origin
The Same-Origin Policy (SOP) is a critical browser security mechanism that prevents JavaScript from making cross-origin requests. Two URLs share the same origin only if all three components match: protocol (http vs https), hostname (example.com), and port (80 vs 443). SOP prevents a malicious site from reading your bank's response via JavaScript. CORS is the controlled mechanism to relax SOP when cross-origin access is genuinely needed.
3How does SQL Injection (SQLi) compromise a web application?
CorrectC: By exploiting vulnerabilities in the web application's input fields to manipulate the backend database queries
SQL Injection occurs when user-supplied input is concatenated directly into SQL queries without sanitization or parameterization. An attacker can inject SQL syntax (e.g., ' OR '1'='1) to modify the query's logic, bypass authentication, exfiltrate entire database contents (UNION SELECT), modify or delete data, or in some configurations execute OS commands (xp_cmdshell on MSSQL). Prevention: always use parameterized queries/prepared statements or ORMs β never string concatenate user input into SQL.
IncorrectC: By exploiting vulnerabilities in the web application's input fields to manipulate the backend database queries
SQL Injection occurs when user-supplied input is concatenated directly into SQL queries without sanitization or parameterization. An attacker can inject SQL syntax (e.g., ' OR '1'='1) to modify the query's logic, bypass authentication, exfiltrate entire database contents (UNION SELECT), modify or delete data, or in some configurations execute OS commands (xp_cmdshell on MSSQL). Prevention: always use parameterized queries/prepared statements or ORMs β never string concatenate user input into SQL.
4What is the primary function of a Web Application Firewall (WAF)?
CorrectD: To inspect, filter, and block malicious Layer 7 HTTP/HTTPS traffic (like XSS or SQLi) directed at a web application
A WAF (Web Application Firewall) operates at OSI Layer 7 (Application layer) and inspects HTTP/HTTPS request and response content β headers, body, cookies, URI parameters β against a ruleset to detect and block web-specific attacks like XSS, SQL injection, CSRF, and SSRF. Unlike traditional network firewalls (Layers 3-4), a WAF understands HTTP semantics. WAFs can be deployed as hardware appliances, software, cloud services (AWS WAF, Cloudflare), or in-application middleware.
IncorrectD: To inspect, filter, and block malicious Layer 7 HTTP/HTTPS traffic (like XSS or SQLi) directed at a web application
A WAF (Web Application Firewall) operates at OSI Layer 7 (Application layer) and inspects HTTP/HTTPS request and response content β headers, body, cookies, URI parameters β against a ruleset to detect and block web-specific attacks like XSS, SQL injection, CSRF, and SSRF. Unlike traditional network firewalls (Layers 3-4), a WAF understands HTTP semantics. WAFs can be deployed as hardware appliances, software, cloud services (AWS WAF, Cloudflare), or in-application middleware.
5What is an IDOR (Insecure Direct Object Reference) vulnerability?
CorrectA: When an application exposes a reference to an internal implementation object, allowing an attacker to bypass authorization and access other users' data
IDOR is an access control vulnerability where an application uses user-controllable input (like a numeric ID: /invoice?id=1234) to directly reference internal objects (database records, files) without verifying that the requesting user is authorized to access that specific object. An attacker simply increments or changes the ID to access other users' records. Prevention: always perform server-side authorization checks on every data access β verify the requesting user owns/is permitted to access the specific object being requested.
IncorrectA: When an application exposes a reference to an internal implementation object, allowing an attacker to bypass authorization and access other users' data
IDOR is an access control vulnerability where an application uses user-controllable input (like a numeric ID: /invoice?id=1234) to directly reference internal objects (database records, files) without verifying that the requesting user is authorized to access that specific object. An attacker simply increments or changes the ID to access other users' records. Prevention: always perform server-side authorization checks on every data access β verify the requesting user owns/is permitted to access the specific object being requested.
6What does a Cross-Site Request Forgery (CSRF) attack attempt to do?
CorrectB: Trick a user's browser into executing an unwanted, authenticated action on a web application where they are currently logged in
CSRF (Cross-Site Request Forgery) exploits the web browser's automatic cookie attachment behavior: when a victim visits a malicious page, that page sends a forged HTTP request to a site where the victim is already authenticated (e.g., /transfer?to=attacker&amount=5000 on their bank). The browser automatically attaches the victim's session cookie, making the server believe the request is legitimate. Prevention: anti-CSRF synchronizer tokens, SameSite=Strict/Lax cookie attribute, and custom request headers (X-Requested-With).
IncorrectB: Trick a user's browser into executing an unwanted, authenticated action on a web application where they are currently logged in
CSRF (Cross-Site Request Forgery) exploits the web browser's automatic cookie attachment behavior: when a victim visits a malicious page, that page sends a forged HTTP request to a site where the victim is already authenticated (e.g., /transfer?to=attacker&amount=5000 on their bank). The browser automatically attaches the victim's session cookie, making the server believe the request is legitimate. Prevention: anti-CSRF synchronizer tokens, SameSite=Strict/Lax cookie attribute, and custom request headers (X-Requested-With).
7What is the primary purpose of implementing a Content Security Policy (CSP) via HTTP headers?
CorrectA: To mitigate XSS and data injection attacks by strictly defining which dynamic resources and scripts the browser is allowed to load
Content Security Policy (CSP) is an HTTP response header that instructs the browser which sources of content are trusted. A strict CSP (e.g., script-src 'self') prevents the browser from executing any inline scripts or scripts from external domains, effectively breaking XSS payloads even if they are injected into the page. CSP also prevents clickjacking (frame-ancestors directive), mixed content, and unauthorized data exfiltration (connect-src, form-action). CSP is one of the most powerful mitigations against client-side attacks.
IncorrectA: To mitigate XSS and data injection attacks by strictly defining which dynamic resources and scripts the browser is allowed to load
Content Security Policy (CSP) is an HTTP response header that instructs the browser which sources of content are trusted. A strict CSP (e.g., script-src 'self') prevents the browser from executing any inline scripts or scripts from external domains, effectively breaking XSS payloads even if they are injected into the page. CSP also prevents clickjacking (frame-ancestors directive), mixed content, and unauthorized data exfiltration (connect-src, form-action). CSP is one of the most powerful mitigations against client-side attacks.
8What does the HttpOnly flag do when applied to a web cookie?
CorrectD: It prevents client-side scripts (like JavaScript) from accessing the cookie, mitigating the risk of XSS token theft
The HttpOnly cookie attribute instructs the browser not to expose the cookie to client-side JavaScript (document.cookie is blocked for HttpOnly cookies). This is a critical XSS mitigation for session cookies: even if an attacker successfully injects a JavaScript payload, they cannot steal the session token because it is inaccessible via JavaScript. The Secure flag (separate attribute) ensures the cookie is only sent over HTTPS. Both HttpOnly and Secure should be set on all session cookies.
IncorrectD: It prevents client-side scripts (like JavaScript) from accessing the cookie, mitigating the risk of XSS token theft
The HttpOnly cookie attribute instructs the browser not to expose the cookie to client-side JavaScript (document.cookie is blocked for HttpOnly cookies). This is a critical XSS mitigation for session cookies: even if an attacker successfully injects a JavaScript payload, they cannot steal the session token because it is inaccessible via JavaScript. The Secure flag (separate attribute) ensures the cookie is only sent over HTTPS. Both HttpOnly and Secure should be set on all session cookies.
9What does the Secure flag do when applied to a web cookie?
CorrectB: It guarantees the cookie is only transmitted over secure, encrypted HTTPS connections, preventing interception
The Secure cookie attribute prevents the browser from sending the cookie over unencrypted HTTP connections β the cookie is transmitted only when the connection uses HTTPS. Without Secure, an SSL-stripping attack (where an attacker downgrades the connection from HTTPS to HTTP) could cause the browser to transmit session cookies in cleartext, exposing them to network interception. Secure should always be set for session cookies alongside HttpOnly and SameSite=Strict.
IncorrectB: It guarantees the cookie is only transmitted over secure, encrypted HTTPS connections, preventing interception
The Secure cookie attribute prevents the browser from sending the cookie over unencrypted HTTP connections β the cookie is transmitted only when the connection uses HTTPS. Without Secure, an SSL-stripping attack (where an attacker downgrades the connection from HTTPS to HTTP) could cause the browser to transmit session cookies in cleartext, exposing them to network interception. Secure should always be set for session cookies alongside HttpOnly and SameSite=Strict.
10What is "Directory Traversal" (or Path Traversal)?
CorrectC: A vulnerability that allows an attacker to read arbitrary files on the server (outside the web root) by manipulating file paths with ../ sequences
Directory (Path) Traversal exploits insufficient input validation when user-supplied file path parameters are used to construct filesystem paths. By injecting ../ sequences (which navigate up a directory level), an attacker can escape the web root directory and read sensitive server files: ../../../etc/passwd (Linux passwords), ../../../../windows/system32/drivers/etc/hosts, or application configuration files containing database credentials. Prevention: validate and canonicalize file paths, use whitelists, and never accept user input to construct file system paths directly.
IncorrectC: A vulnerability that allows an attacker to read arbitrary files on the server (outside the web root) by manipulating file paths with ../ sequences
Directory (Path) Traversal exploits insufficient input validation when user-supplied file path parameters are used to construct filesystem paths. By injecting ../ sequences (which navigate up a directory level), an attacker can escape the web root directory and read sensitive server files: ../../../etc/passwd (Linux passwords), ../../../../windows/system32/drivers/etc/hosts, or application configuration files containing database credentials. Prevention: validate and canonicalize file paths, use whitelists, and never accept user input to construct file system paths directly.
11What is the fundamental difference between Authentication and Authorization?
CorrectC: Authentication verifies who the user is; Authorization verifies what the user is allowed to do or access
Authentication (AuthN) answers "Who are you?" β verifying identity via credentials (password, MFA, certificate). Authorization (AuthZ) answers "What can you do?" β determining what resources and actions the authenticated identity is permitted to access. In web security, IDOR and Broken Access Control vulnerabilities are authorization failures; credential stuffing and brute force attacks are authentication attacks. Identity providers handle AuthN; RBAC/ABAC policies handle AuthZ. These must be implemented separately and correctly.
IncorrectC: Authentication verifies who the user is; Authorization verifies what the user is allowed to do or access
Authentication (AuthN) answers "Who are you?" β verifying identity via credentials (password, MFA, certificate). Authorization (AuthZ) answers "What can you do?" β determining what resources and actions the authenticated identity is permitted to access. In web security, IDOR and Broken Access Control vulnerabilities are authorization failures; credential stuffing and brute force attacks are authentication attacks. Identity providers handle AuthN; RBAC/ABAC policies handle AuthZ. These must be implemented separately and correctly.
12What does CORS (Cross-Origin Resource Sharing) allow a web server to do?
CorrectD: To safely relax the Same-Origin Policy and specify exactly which external domains are permitted to access its resources
CORS is a W3C mechanism that uses HTTP headers to allow servers to specify which foreign origins can make cross-origin requests. The server sends Access-Control-Allow-Origin headers indicating permitted origins. CORS enables legitimate cross-origin API calls (e.g., a React app on app.example.com calling api.example.com). CORS misconfiguration β setting Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true β is a critical vulnerability that allows any malicious site to read authenticated data from the API.
IncorrectD: To safely relax the Same-Origin Policy and specify exactly which external domains are permitted to access its resources
CORS is a W3C mechanism that uses HTTP headers to allow servers to specify which foreign origins can make cross-origin requests. The server sends Access-Control-Allow-Origin headers indicating permitted origins. CORS enables legitimate cross-origin API calls (e.g., a React app on app.example.com calling api.example.com). CORS misconfiguration β setting Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true β is a critical vulnerability that allows any malicious site to read authenticated data from the API.
13What is "Session Hijacking"?
CorrectB: An attacker intercepting or stealing a valid session token (like a cookie) to impersonate an authenticated user
Session Hijacking occurs when an attacker obtains a valid session token (typically from a session cookie) and uses it to impersonate the legitimate authenticated user β bypassing authentication entirely. Vectors: XSS (stealing cookies via document.cookie if HttpOnly is absent), network sniffing on unencrypted HTTP, predictable session IDs, MITM attacks. Mitigations: HttpOnly + Secure + SameSite cookies, HTTPS everywhere, short session timeouts, session token regeneration after login.
IncorrectB: An attacker intercepting or stealing a valid session token (like a cookie) to impersonate an authenticated user
Session Hijacking occurs when an attacker obtains a valid session token (typically from a session cookie) and uses it to impersonate the legitimate authenticated user β bypassing authentication entirely. Vectors: XSS (stealing cookies via document.cookie if HttpOnly is absent), network sniffing on unencrypted HTTP, predictable session IDs, MITM attacks. Mitigations: HttpOnly + Secure + SameSite cookies, HTTPS everywhere, short session timeouts, session token regeneration after login.
14In web security, what does OWASP stand for?
CorrectB: Open Worldwide Application Security Project
OWASP (Open Worldwide Application Security Project) is a nonprofit foundation dedicated to improving software security. It produces the globally recognized OWASP Top 10 β a regularly updated list of the most critical web application security risks (e.g., Injection, Broken Access Control, Cryptographic Failures, XSS, SSRF). OWASP also produces the ASVS (Application Security Verification Standard), WebGoat (training app), ZAP (Zed Attack Proxy), and the Cheat Sheet Series for developers.
IncorrectB: Open Worldwide Application Security Project
OWASP (Open Worldwide Application Security Project) is a nonprofit foundation dedicated to improving software security. It produces the globally recognized OWASP Top 10 β a regularly updated list of the most critical web application security risks (e.g., Injection, Broken Access Control, Cryptographic Failures, XSS, SSRF). OWASP also produces the ASVS (Application Security Verification Standard), WebGoat (training app), ZAP (Zed Attack Proxy), and the Cheat Sheet Series for developers.
15What is a "Web Shell"?
CorrectA: A malicious script uploaded to a compromised web server that grants the attacker remote administrative control
A web shell is a malicious script (PHP, ASP, JSP, etc.) uploaded to a compromised web server β usually via unrestricted file upload, remote file inclusion, or code execution vulnerabilities. Once installed, it provides the attacker with a browser-accessible backdoor to execute OS commands, browse the file system, exfiltrate data, and pivot to internal networks. Detection: file integrity monitoring, WAF rules detecting shell command patterns, and monitoring for unexpected outbound connections.
IncorrectA: A malicious script uploaded to a compromised web server that grants the attacker remote administrative control
A web shell is a malicious script (PHP, ASP, JSP, etc.) uploaded to a compromised web server β usually via unrestricted file upload, remote file inclusion, or code execution vulnerabilities. Once installed, it provides the attacker with a browser-accessible backdoor to execute OS commands, browse the file system, exfiltrate data, and pivot to internal networks. Detection: file integrity monitoring, WAF rules detecting shell command patterns, and monitoring for unexpected outbound connections.
16Why is proper "Input Validation" critical for web applications?
CorrectD: Because unvalidated or unsanitized user input is the root cause of injection attacks (like SQLi and XSS)
The majority of web application vulnerabilities share a single root cause: trusting and unsafely processing user-controlled input. Input validation (rejecting input that does not conform to expected format/length/type), input sanitization (removing or escaping dangerous characters), and output encoding (encoding data before rendering it in HTML/SQL/commands) together form the defense-in-depth against injection attacks. The OWASP "Injection" category and "XSS" category are both fundamentally input handling failures.
IncorrectD: Because unvalidated or unsanitized user input is the root cause of injection attacks (like SQLi and XSS)
The majority of web application vulnerabilities share a single root cause: trusting and unsafely processing user-controlled input. Input validation (rejecting input that does not conform to expected format/length/type), input sanitization (removing or escaping dangerous characters), and output encoding (encoding data before rendering it in HTML/SQL/commands) together form the defense-in-depth against injection attacks. The OWASP "Injection" category and "XSS" category are both fundamentally input handling failures.
17What is "Clickjacking" (UI Redressing)?
CorrectB: Tricking a user into clicking a deceptive, invisible, or disguised element on a webpage (often using transparent iframes) to execute unintended actions
Clickjacking embeds a target website in a transparent iframe layered over a deceptive decoy page. The victim believes they are clicking on the visible decoy (e.g., a "Win a Prize!" button), but they are actually clicking on an invisible element of the target site (e.g., "Confirm Purchase" or "Enable Camera"). Prevention: X-Frame-Options: DENY or SAMEORIGIN header, Content-Security-Policy frame-ancestors directive. These instruct browsers to refuse iframe embedding of the protected page.
IncorrectB: Tricking a user into clicking a deceptive, invisible, or disguised element on a webpage (often using transparent iframes) to execute unintended actions
Clickjacking embeds a target website in a transparent iframe layered over a deceptive decoy page. The victim believes they are clicking on the visible decoy (e.g., a "Win a Prize!" button), but they are actually clicking on an invisible element of the target site (e.g., "Confirm Purchase" or "Enable Camera"). Prevention: X-Frame-Options: DENY or SAMEORIGIN header, Content-Security-Policy frame-ancestors directive. These instruct browsers to refuse iframe embedding of the protected page.
18What is the primary purpose of API Rate Limiting?
CorrectB: To prevent brute-force attacks, credential stuffing, and DoS attacks by restricting the number of requests a client can make in a given timeframe
API Rate Limiting restricts how many requests a client (identified by IP, API key, or user ID) can make within a defined time window. This prevents: brute-force password attacks (requiring millions of login attempts), credential stuffing (replaying breached credentials at high speed), enumeration attacks (scraping all user records via IDOR), and volumetric DoS attacks. HTTP 429 Too Many Requests is returned when the limit is exceeded. Exponential backoff with lockout further frustrates automated attack tools.
IncorrectB: To prevent brute-force attacks, credential stuffing, and DoS attacks by restricting the number of requests a client can make in a given timeframe
API Rate Limiting restricts how many requests a client (identified by IP, API key, or user ID) can make within a defined time window. This prevents: brute-force password attacks (requiring millions of login attempts), credential stuffing (replaying breached credentials at high speed), enumeration attacks (scraping all user records via IDOR), and volumetric DoS attacks. HTTP 429 Too Many Requests is returned when the limit is exceeded. Exponential backoff with lockout further frustrates automated attack tools.
19What is a "Man-in-the-Middle" (MitM) attack in web traffic?
CorrectA: An attacker secretly intercepting, reading, and potentially altering the communications between a client and a server
In a MitM (Man-in-the-Middle) attack, the attacker positions themselves between a client and server, secretly relaying and potentially modifying traffic. The victim believes they have a direct connection to the legitimate server. Vectors: ARP spoofing on LAN, rogue Wi-Fi access points, SSL stripping attacks. Defenses: HTTPS (TLS), HSTS (HTTP Strict Transport Security), certificate pinning, mutual TLS (mTLS), and public key infrastructure (PKI) validation.
IncorrectA: An attacker secretly intercepting, reading, and potentially altering the communications between a client and a server
In a MitM (Man-in-the-Middle) attack, the attacker positions themselves between a client and server, secretly relaying and potentially modifying traffic. The victim believes they have a direct connection to the legitimate server. Vectors: ARP spoofing on LAN, rogue Wi-Fi access points, SSL stripping attacks. Defenses: HTTPS (TLS), HSTS (HTTP Strict Transport Security), certificate pinning, mutual TLS (mTLS), and public key infrastructure (PKI) validation.
20Which of the following is an example of a "Business Logic" vulnerability?
CorrectD: Applying an e-commerce discount code multiple times recursively to force the cart total below zero
Business Logic vulnerabilities exploit flaws in the designed workflow of an application rather than technical implementation errors. They cannot be detected by generic scanners because they require understanding intended business rules. Examples: applying the same discount code multiple times, transferring negative amounts, manipulating price parameters in checkout, bypassing multi-step workflows (directly POSTing to a final step), or race conditions in limited-quantity purchases. Prevention requires deep testing of all state transitions and business rule enforcement on the server side.
IncorrectD: Applying an e-commerce discount code multiple times recursively to force the cart total below zero
Business Logic vulnerabilities exploit flaws in the designed workflow of an application rather than technical implementation errors. They cannot be detected by generic scanners because they require understanding intended business rules. Examples: applying the same discount code multiple times, transferring negative amounts, manipulating price parameters in checkout, bypassing multi-step workflows (directly POSTing to a final step), or race conditions in limited-quantity purchases. Prevention requires deep testing of all state transitions and business rule enforcement on the server side.
Web Security β Advanced
1What is an XXE (XML External Entity) attack?
CorrectC: Exploiting a poorly configured XML parser to read arbitrary local files, interact with internal networks, or execute SSRF via malicious entity references
XXE (XML External Entity) Injection targets XML parsers that support external entity resolution. An attacker submits crafted XML containing external entity declarations (e.g., <!ENTITY xxe SYSTEM "file:///etc/passwd">) and references them in the document; the parser fetches and returns the referenced content. Impact: read arbitrary local files (credentials, config files), perform SSRF against internal systems, cause DoS via "Billion Laughs" entity expansion. Prevention: disable DTD processing and external entity resolution in XML parsers.
IncorrectC: Exploiting a poorly configured XML parser to read arbitrary local files, interact with internal networks, or execute SSRF via malicious entity references
XXE (XML External Entity) Injection targets XML parsers that support external entity resolution. An attacker submits crafted XML containing external entity declarations (e.g., <!ENTITY xxe SYSTEM "file:///etc/passwd">) and references them in the document; the parser fetches and returns the referenced content. Impact: read arbitrary local files (credentials, config files), perform SSRF against internal systems, cause DoS via "Billion Laughs" entity expansion. Prevention: disable DTD processing and external entity resolution in XML parsers.
2How does Server-Side Request Forgery (SSRF) operate?
CorrectA: The attacker tricks the web application backend server into making HTTP requests to an arbitrary domain or internal, protected resource on the attacker's behalf
SSRF (Server-Side Request Forgery) exploits server-side functionality that fetches remote resources (URL fetcher, webhook, PDF generator, image downloader). An attacker supplies a malicious URL pointing to an internal resource the server can reach but the attacker cannot directly: http://169.254.169.254/latest/meta-data/ (AWS IMDSv1 metadata service), internal APIs, or other backend systems behind firewalls. This is how the Capital One breach occurred β SSRF via AWS metadata service exposed IAM credentials. IMDSv2 with session tokens mitigates this.
IncorrectA: The attacker tricks the web application backend server into making HTTP requests to an arbitrary domain or internal, protected resource on the attacker's behalf
SSRF (Server-Side Request Forgery) exploits server-side functionality that fetches remote resources (URL fetcher, webhook, PDF generator, image downloader). An attacker supplies a malicious URL pointing to an internal resource the server can reach but the attacker cannot directly: http://169.254.169.254/latest/meta-data/ (AWS IMDSv1 metadata service), internal APIs, or other backend systems behind firewalls. This is how the Capital One breach occurred β SSRF via AWS metadata service exposed IAM credentials. IMDSv2 with session tokens mitigates this.
3What are the three standard components of a JSON Web Token (JWT)?
CorrectB: Header, Payload, Signature
A JWT consists of three Base64url-encoded parts separated by dots (xxxxx.yyyyy.zzzzz): (1) Header β specifies the token type and signing algorithm (e.g., {"alg":"HS256","typ":"JWT"}); (2) Payload β contains claims (assertions about the user and metadata: sub, exp, iat, roles); (3) Signature β created by the server signing the encoded Header + Payload with a secret/private key, used to verify the token hasn't been tampered with. JWTs are commonly used as Bearer tokens in Authorization headers.
IncorrectB: Header, Payload, Signature
A JWT consists of three Base64url-encoded parts separated by dots (xxxxx.yyyyy.zzzzz): (1) Header β specifies the token type and signing algorithm (e.g., {"alg":"HS256","typ":"JWT"}); (2) Payload β contains claims (assertions about the user and metadata: sub, exp, iat, roles); (3) Signature β created by the server signing the encoded Header + Payload with a secret/private key, used to verify the token hasn't been tampered with. JWTs are commonly used as Bearer tokens in Authorization headers.
4What is a highly critical vulnerability associated with poorly implemented JWT validation?
CorrectC: The application accepts tokens where the "alg" header has been maliciously changed to "none", allowing the attacker to bypass the signature verification entirely
The "alg:none" attack exploits JWT libraries that accept tokens with no signature when alg is set to "none". An attacker decodes a legitimate JWT, modifies the payload (escalating privileges), sets alg to "none", removes the signature, and submits it. A vulnerable library skips verification because alg:none means "no signature verification needed." Prevention: explicitly whitelist accepted algorithms in the JWT library configuration, never accept alg:none, and prefer asymmetric algorithms (RS256, ES256) over symmetric (HS256) for scalability.
IncorrectC: The application accepts tokens where the "alg" header has been maliciously changed to "none", allowing the attacker to bypass the signature verification entirely
The "alg:none" attack exploits JWT libraries that accept tokens with no signature when alg is set to "none". An attacker decodes a legitimate JWT, modifies the payload (escalating privileges), sets alg to "none", removes the signature, and submits it. A vulnerable library skips verification because alg:none means "no signature verification needed." Prevention: explicitly whitelist accepted algorithms in the JWT library configuration, never accept alg:none, and prefer asymmetric algorithms (RS256, ES256) over symmetric (HS256) for scalability.
5What is the fundamental mechanism behind HTTP Request Smuggling?
CorrectA: Exploiting discrepancies in how front-end proxies and back-end servers parse conflicting Content-Length and Transfer-Encoding headers, allowing attackers to "smuggle" hidden requests
HTTP Request Smuggling exploits ambiguity between the Content-Length and Transfer-Encoding: chunked headers. When a front-end proxy and back-end server interpret which header takes precedence differently, an attacker can craft a request that the proxy treats as one full request but the back-end treats as two β effectively prepending attacker-controlled content to the next legitimate user's request. This enables cache poisoning, WAF bypass, credential hijacking, and response splitting. Discovered and popularized by James Kettle (PortSwigger).
IncorrectA: Exploiting discrepancies in how front-end proxies and back-end servers parse conflicting Content-Length and Transfer-Encoding headers, allowing attackers to "smuggle" hidden requests
HTTP Request Smuggling exploits ambiguity between the Content-Length and Transfer-Encoding: chunked headers. When a front-end proxy and back-end server interpret which header takes precedence differently, an attacker can craft a request that the proxy treats as one full request but the back-end treats as two β effectively prepending attacker-controlled content to the next legitimate user's request. This enables cache poisoning, WAF bypass, credential hijacking, and response splitting. Discovered and popularized by James Kettle (PortSwigger).
6What is the primary danger of "Insecure Deserialization" in web applications?
CorrectB: Untrusted, serialized data is instantiated into objects without validation, which can be manipulated by an attacker to achieve Remote Code Execution (RCE)
Insecure Deserialization (OWASP A08:2021) occurs when applications deserialize objects from untrusted sources (cookies, headers, API parameters, file uploads) without first validating their integrity. Attackers craft malicious serialized payloads that, when deserialized, instantiate or manipulate objects in ways that trigger gadget chains, leading to Remote Code Execution, privilege escalation, or data tampering. Languages with complex serialization ecosystems (Java, PHP, Python pickle, .NET) are particularly vulnerable. Prevention: avoid deserializing untrusted data; if unavoidable, use integrity checks (digital signatures) before deserialization.
IncorrectB: Untrusted, serialized data is instantiated into objects without validation, which can be manipulated by an attacker to achieve Remote Code Execution (RCE)
Insecure Deserialization (OWASP A08:2021) occurs when applications deserialize objects from untrusted sources (cookies, headers, API parameters, file uploads) without first validating their integrity. Attackers craft malicious serialized payloads that, when deserialized, instantiate or manipulate objects in ways that trigger gadget chains, leading to Remote Code Execution, privilege escalation, or data tampering. Languages with complex serialization ecosystems (Java, PHP, Python pickle, .NET) are particularly vulnerable. Prevention: avoid deserializing untrusted data; if unavoidable, use integrity checks (digital signatures) before deserialization.
7How does a DOM-based XSS attack differ from Reflected or Stored XSS?
CorrectC: The vulnerability exists entirely in the client-side JavaScript modifying the Document Object Model; the malicious payload never actually reaches the backend server
DOM-based XSS occurs when vulnerable client-side JavaScript reads attacker-controlled data (hash, URL parameter, referrer, postMessage) and writes it unsafely to the DOM (innerHTML, document.write, eval) β entirely on the client side, with no server involvement. This makes DOM XSS invisible to server-side WAFs and input validation. Reflected XSS has the server echo unsanitized input; Stored XSS persists the payload in the database. DOM XSS requires code review of client-side JavaScript source sinks and sources to detect.
IncorrectC: The vulnerability exists entirely in the client-side JavaScript modifying the Document Object Model; the malicious payload never actually reaches the backend server
DOM-based XSS occurs when vulnerable client-side JavaScript reads attacker-controlled data (hash, URL parameter, referrer, postMessage) and writes it unsafely to the DOM (innerHTML, document.write, eval) β entirely on the client side, with no server involvement. This makes DOM XSS invisible to server-side WAFs and input validation. Reflected XSS has the server echo unsanitized input; Stored XSS persists the payload in the database. DOM XSS requires code review of client-side JavaScript source sinks and sources to detect.
8In the OAuth 2.0 authorization framework, what is the role of the Authorization Server?
CorrectA: It securely authenticates the user and issues access tokens to the client application
In OAuth 2.0, four roles interact: Resource Owner (the user), Client (third-party app requesting access), Resource Server (API hosting protected data), and Authorization Server (the trusted identity provider β Google, GitHub, Okta β that authenticates the user and issues access tokens). The client redirects the user to the Authorization Server, which authenticates them and returns an authorization code; the client exchanges this for an access token; the client uses the access token to call the Resource Server API. OAuth flaws (open redirect, state parameter missing, token leakage) are a rich source of real-world vulnerabilities.
IncorrectA: It securely authenticates the user and issues access tokens to the client application
In OAuth 2.0, four roles interact: Resource Owner (the user), Client (third-party app requesting access), Resource Server (API hosting protected data), and Authorization Server (the trusted identity provider β Google, GitHub, Okta β that authenticates the user and issues access tokens). The client redirects the user to the Authorization Server, which authenticates them and returns an authorization code; the client exchanges this for an access token; the client uses the access token to call the Resource Server API. OAuth flaws (open redirect, state parameter missing, token leakage) are a rich source of real-world vulnerabilities.
9What is a "Subdomain Takeover"?
CorrectB: When a DNS record points to a de-provisioned external service (like AWS S3 or GitHub Pages), allowing an attacker to claim that service space and hijack the subdomain
Subdomain Takeover occurs when a DNS CNAME record (e.g., staging.example.com CNAME exampleapp.azurewebsites.net) continues to exist after the external service it points to has been deprovisioned. An attacker claims the now-available external service slot (registers the same Azure app name, claims the S3 bucket name), serving malicious content from the legitimate subdomain. This enables cookie theft (since cookies are scoped to the domain), phishing under a trusted brand, and CSP bypass. Prevention: remove stale DNS records when deprovisioning external services.
IncorrectB: When a DNS record points to a de-provisioned external service (like AWS S3 or GitHub Pages), allowing an attacker to claim that service space and hijack the subdomain
Subdomain Takeover occurs when a DNS CNAME record (e.g., staging.example.com CNAME exampleapp.azurewebsites.net) continues to exist after the external service it points to has been deprovisioned. An attacker claims the now-available external service slot (registers the same Azure app name, claims the S3 bucket name), serving malicious content from the legitimate subdomain. This enables cookie theft (since cookies are scoped to the domain), phishing under a trusted brand, and CSP bypass. Prevention: remove stale DNS records when deprovisioning external services.
10What does the HTTP Strict Transport Security (HSTS) header achieve?
CorrectB: It instructs the browser that the website must only be accessed using secure HTTPS connections, preventing SSL-stripping and downgrade attacks
HSTS (HTTP Strict Transport Security) is an HTTP response header (Strict-Transport-Security: max-age=31536000; includeSubDomains; preload) that instructs the browser to always use HTTPS for the domain, refusing any HTTP connection β even if the user manually types http:// or follows an HTTP link. This prevents SSL-stripping attacks (where a MitM downgrades the connection before the TLS handshake). The preload directive submits the domain to browser-maintained HSTS preload lists, offering protection on first visit.
IncorrectB: It instructs the browser that the website must only be accessed using secure HTTPS connections, preventing SSL-stripping and downgrade attacks
HSTS (HTTP Strict Transport Security) is an HTTP response header (Strict-Transport-Security: max-age=31536000; includeSubDomains; preload) that instructs the browser to always use HTTPS for the domain, refusing any HTTP connection β even if the user manually types http:// or follows an HTTP link. This prevents SSL-stripping attacks (where a MitM downgrades the connection before the TLS handshake). The preload directive submits the domain to browser-maintained HSTS preload lists, offering protection on first visit.
11What is a Server-Side Template Injection (SSTI)?
CorrectD: Injecting native template syntax (e.g., Jinja2, Twig) into user input, which is then unsafely evaluated by the server, often leading to Remote Code Execution
SSTI occurs when a web application embeds user-supplied input directly into a server-side template that is then rendered by a template engine. Attackers inject template-native expressions ({{7*7}} in Jinja2, ${7*7} in Freemarker) which the engine evaluates β often with access to internal object hierarchies that allow OS command execution. SSTI is frequently mistaken for XSS during initial testing. It is identified by template-specific payloads that return evaluated results (e.g., returning 49 for {{7*7}}). Prevention: sandbox template contexts, never pass user input as template code, use template engines with sandboxing.
IncorrectD: Injecting native template syntax (e.g., Jinja2, Twig) into user input, which is then unsafely evaluated by the server, often leading to Remote Code Execution
SSTI occurs when a web application embeds user-supplied input directly into a server-side template that is then rendered by a template engine. Attackers inject template-native expressions ({{7*7}} in Jinja2, ${7*7} in Freemarker) which the engine evaluates β often with access to internal object hierarchies that allow OS command execution. SSTI is frequently mistaken for XSS during initial testing. It is identified by template-specific payloads that return evaluated results (e.g., returning 49 for {{7*7}}). Prevention: sandbox template contexts, never pass user input as template code, use template engines with sandboxing.
12What is the primary security risk of an "Open Redirect" vulnerability?
CorrectB: It allows attackers to craft highly credible phishing links or steal OAuth access tokens by redirecting legitimate authentication flows to a malicious domain
An Open Redirect occurs when an application uses unvalidated user-controlled input to construct a redirect URL: /redirect?url=https://evil.com. Attackers use the trusted domain as a redirect wrapper, making phishing URLs highly credible (https://trusted.com/login?next=https://evil.com/steal-token). More critically, Open Redirects can be chained with OAuth flows to steal authorization codes: an attacker registers a redirect_uri pointing to the open redirect endpoint, causing the authorization server to send the code to the attacker's site. Prevention: whitelist permitted redirect destinations.
IncorrectB: It allows attackers to craft highly credible phishing links or steal OAuth access tokens by redirecting legitimate authentication flows to a malicious domain
An Open Redirect occurs when an application uses unvalidated user-controlled input to construct a redirect URL: /redirect?url=https://evil.com. Attackers use the trusted domain as a redirect wrapper, making phishing URLs highly credible (https://trusted.com/login?next=https://evil.com/steal-token). More critically, Open Redirects can be chained with OAuth flows to steal authorization codes: an attacker registers a redirect_uri pointing to the open redirect endpoint, causing the authorization server to send the code to the attacker's site. Prevention: whitelist permitted redirect destinations.
13How do you securely mitigate CSRF vulnerabilities in a stateless API architecture?
CorrectC: By using Anti-CSRF synchronizer tokens or implementing strict SameSite cookie attributes
CSRF mitigation strategies: (1) Synchronizer Token Pattern β embed a random, secret, per-session CSRF token in forms/headers that the server validates on submission; (2) SameSite=Strict cookie attribute β prevents cookies from being sent with cross-origin requests, blocking CSRF at the browser level without server-side tokens; (3) Double Submit Cookie β send the same random value in a cookie and a hidden form field, verifying they match. For stateless SPAs using Authorization: Bearer header instead of cookies, CSRF is inherently prevented because browsers do not auto-attach custom headers to cross-origin requests.
IncorrectC: By using Anti-CSRF synchronizer tokens or implementing strict SameSite cookie attributes
CSRF mitigation strategies: (1) Synchronizer Token Pattern β embed a random, secret, per-session CSRF token in forms/headers that the server validates on submission; (2) SameSite=Strict cookie attribute β prevents cookies from being sent with cross-origin requests, blocking CSRF at the browser level without server-side tokens; (3) Double Submit Cookie β send the same random value in a cookie and a hidden form field, verifying they match. For stateless SPAs using Authorization: Bearer header instead of cookies, CSRF is inherently prevented because browsers do not auto-attach custom headers to cross-origin requests.
14How does "Blind SQL Injection" differ from traditional SQL Injection?
CorrectC: The application does not return database errors or data directly to the screen; the attacker must infer information by asking boolean true/false questions or measuring time delays
Blind SQLi is used when an application is vulnerable to injection but does not display query results or error messages to the user. Two subtypes: (1) Boolean-based Blind β attacker injects conditions that change the application's behavior (returns different page for true vs false), extracting data bit-by-bit through binary search; (2) Time-based Blind β injects time-delay functions (SLEEP(5), WAITFOR DELAY) and measures response time to infer truth values. Both are significantly slower than in-band injection but equally impactful. SQLMap automates both.
IncorrectC: The application does not return database errors or data directly to the screen; the attacker must infer information by asking boolean true/false questions or measuring time delays
Blind SQLi is used when an application is vulnerable to injection but does not display query results or error messages to the user. Two subtypes: (1) Boolean-based Blind β attacker injects conditions that change the application's behavior (returns different page for true vs false), extracting data bit-by-bit through binary search; (2) Time-based Blind β injects time-delay functions (SLEEP(5), WAITFOR DELAY) and measures response time to infer truth values. Both are significantly slower than in-band injection but equally impactful. SQLMap automates both.
15What is a critical security risk regarding CORS misconfiguration?
CorrectB: Setting Access-Control-Allow-Origin: * in combination with Access-Control-Allow-Credentials: true, allowing any malicious site to read sensitive authenticated data
The most critical CORS misconfiguration is reflecting the Origin header as ACAO (Access-Control-Allow-Origin) with ACAC: true (Access-Control-Allow-Credentials: true). This allows any attacker-controlled site to make credentialed cross-origin requests to the API and read the responses β including session data and personal information. Note: ACAO: * (wildcard) combined with ACAC: true is explicitly invalid per the spec, but some servers reflect the Origin header dynamically, effectively granting any origin full credentialed access.
IncorrectB: Setting Access-Control-Allow-Origin: * in combination with Access-Control-Allow-Credentials: true, allowing any malicious site to read sensitive authenticated data
The most critical CORS misconfiguration is reflecting the Origin header as ACAO (Access-Control-Allow-Origin) with ACAC: true (Access-Control-Allow-Credentials: true). This allows any attacker-controlled site to make credentialed cross-origin requests to the API and read the responses β including session data and personal information. Note: ACAO: * (wildcard) combined with ACAC: true is explicitly invalid per the spec, but some servers reflect the Origin header dynamically, effectively granting any origin full credentialed access.
16In which programming language does "Prototype Pollution" occur, allowing an attacker to inject properties into base object prototypes?
CorrectB: JavaScript (Node.js/Client-side)
Prototype Pollution is a JavaScript-specific vulnerability where an attacker can inject properties into JavaScript's base Object.prototype using specially crafted property names like __proto__, constructor, or prototype in JSON payloads or query parameters. Since all JavaScript objects inherit from Object.prototype, polluting it affects all objects in the runtime. Impact ranges from property injection for logic bypass (e.g., setting isAdmin: true on prototype) to Remote Code Execution in Node.js via gadget chains in popular libraries (lodash merge, jQuery extend were historically vulnerable).
IncorrectB: JavaScript (Node.js/Client-side)
Prototype Pollution is a JavaScript-specific vulnerability where an attacker can inject properties into JavaScript's base Object.prototype using specially crafted property names like __proto__, constructor, or prototype in JSON payloads or query parameters. Since all JavaScript objects inherit from Object.prototype, polluting it affects all objects in the runtime. Impact ranges from property injection for logic bypass (e.g., setting isAdmin: true on prototype) to Remote Code Execution in Node.js via gadget chains in popular libraries (lodash merge, jQuery extend were historically vulnerable).
17What is the purpose of using a "Canary Token" (or Honeytoken) in web application security?
CorrectA: To provide a fake piece of data or credential that alerts defenders immediately if it is ever accessed, indicating a breach or unauthorized access
A Canary Token (honeytoken) is a deliberate decoy resource β a fake API key, credential, URL, or file β planted in locations an attacker would access if they had compromised the system (source code, config files, backups). When accessed, the token fires an alert to defenders with the attacker's IP, time, and access context. Unlike other detection mechanisms, honeytokens have zero legitimate uses, meaning any access is unambiguously malicious. Tools like CanaryTokens.org provide easy deployment. They are effective for detecting insider threats and external breaches that standard logging might miss.
IncorrectA: To provide a fake piece of data or credential that alerts defenders immediately if it is ever accessed, indicating a breach or unauthorized access
A Canary Token (honeytoken) is a deliberate decoy resource β a fake API key, credential, URL, or file β planted in locations an attacker would access if they had compromised the system (source code, config files, backups). When accessed, the token fires an alert to defenders with the attacker's IP, time, and access context. Unlike other detection mechanisms, honeytokens have zero legitimate uses, meaning any access is unambiguously malicious. Tools like CanaryTokens.org provide easy deployment. They are effective for detecting insider threats and external breaches that standard logging might miss.
18What is an HTTP Parameter Pollution (HPP) attack?
CorrectB: Supplying multiple parameters with the exact same name in an HTTP request to manipulate backend application logic or bypass WAF rules
HTTP Parameter Pollution (HPP) exploits inconsistent behavior between HTTP frameworks and WAFs when multiple parameters share the same name (e.g., ?role=user&role=admin). Different frameworks handle duplicates differently: PHP/Apache uses the last value, ASP.NET uses the first, Express.js creates an array. Attackers use this to: bypass WAF rules (split a malicious payload across duplicate parameters so each half appears benign), override server-side parameter values, and exploit inconsistencies between a WAF and the backend application. Prevention: define and enforce explicit parameter handling policies.
IncorrectB: Supplying multiple parameters with the exact same name in an HTTP request to manipulate backend application logic or bypass WAF rules
HTTP Parameter Pollution (HPP) exploits inconsistent behavior between HTTP frameworks and WAFs when multiple parameters share the same name (e.g., ?role=user&role=admin). Different frameworks handle duplicates differently: PHP/Apache uses the last value, ASP.NET uses the first, Express.js creates an array. Attackers use this to: bypass WAF rules (split a malicious payload across duplicate parameters so each half appears benign), override server-side parameter values, and exploit inconsistencies between a WAF and the backend application. Prevention: define and enforce explicit parameter handling policies.
19What is a primary security concern with WebSockets compared to standard HTTP requests?
CorrectC: WebSockets do not strictly enforce the Same-Origin Policy (SOP) by default, making them highly vulnerable to Cross-Site WebSocket Hijacking (CSWSH) if origin headers aren't validated
WebSockets upgrade an HTTP connection to a persistent bidirectional channel (ws:// or wss://). Unlike XMLHttpRequest, the browser does NOT enforce the Same-Origin Policy for WebSocket connections β it will send cookies with WebSocket handshake requests to any origin. This enables Cross-Site WebSocket Hijacking (CSWSH): a malicious page opens a WebSocket connection to the victim's application, which attaches session cookies, allowing the attacker to receive real-time data. Prevention: always validate the Origin header in the WebSocket handshake, and require CSRF tokens.
IncorrectC: WebSockets do not strictly enforce the Same-Origin Policy (SOP) by default, making them highly vulnerable to Cross-Site WebSocket Hijacking (CSWSH) if origin headers aren't validated
WebSockets upgrade an HTTP connection to a persistent bidirectional channel (ws:// or wss://). Unlike XMLHttpRequest, the browser does NOT enforce the Same-Origin Policy for WebSocket connections β it will send cookies with WebSocket handshake requests to any origin. This enables Cross-Site WebSocket Hijacking (CSWSH): a malicious page opens a WebSocket connection to the victim's application, which attaches session cookies, allowing the attacker to receive real-time data. Prevention: always validate the Origin header in the WebSocket handshake, and require CSRF tokens.
20What is "Credential Stuffing"?
CorrectB: Using massive lists of compromised username/password pairs from previous data breaches to automate login attempts on other web applications
Credential stuffing exploits password reuse: attackers obtain breached credential databases (billions of username:password pairs from past breaches β available on dark web marketplaces) and use automation tools (Sentry MBA, OpenBullet) to test these credentials against other services at high speed. Because many users reuse passwords across sites, this succeeds at scale despite no brute-forcing of the target site itself. Defenses: MFA (most effective), bot detection (CAPTCHA, fingerprinting), rate limiting/IP blocking, breached password detection (HaveIBeenPwned API), and behavioral analytics.
IncorrectB: Using massive lists of compromised username/password pairs from previous data breaches to automate login attempts on other web applications
Credential stuffing exploits password reuse: attackers obtain breached credential databases (billions of username:password pairs from past breaches β available on dark web marketplaces) and use automation tools (Sentry MBA, OpenBullet) to test these credentials against other services at high speed. Because many users reuse passwords across sites, this succeeds at scale despite no brute-forcing of the target site itself. Defenses: MFA (most effective), bot detection (CAPTCHA, fingerprinting), rate limiting/IP blocking, breached password detection (HaveIBeenPwned API), and behavioral analytics.
Conclusion: Mastering Web Security
These 60 MCQs cover the full spectrum of web security knowledge β from understanding why HTTPS uses port 443, through systematically applying the OWASP Top 10 attack taxonomy, to exploiting advanced research-level vulnerabilities like HTTP Request Smuggling and JWT algorithm confusion attacks.
The key mental model: almost every web vulnerability is a trust boundary failure. XSS is the server trusting user input in HTML output. SQLi is the database trusting user input in queries. CSRF is the server trusting the browser's automatic cookie attachment. SSRF is the server trusting user-supplied URLs. Understanding which trust boundary each attack exploits makes the entire attack taxonomy systematic.
After completing this set, complement your knowledge with the full Web Security theory notes and explore the OWASP Top 10 MCQ library for deeper coverage of each category with attack-and-defense pairing.
Key Takeaways β Web Security
- XSS injects scripts into HTML output β mitigate with output encoding, CSP, and HttpOnly cookies.
- SQLi injects SQL into queries β mitigate with parameterized queries/prepared statements (never string concatenation).
- CSRF forges authenticated requests β mitigate with anti-CSRF tokens, SameSite cookies.
- SSRF forces the server to fetch internal resources β mitigate with URL allowlists, IMDSv2, and network segmentation.
- IDOR = missing server-side authorization on object access β always validate ownership server-side.
- JWT alg:none β always explicitly whitelist accepted algorithms; never trust the token header's alg claim.
- HttpOnly prevents JS cookie access (anti-XSS); Secure prevents HTTP transmission; SameSite=Strict prevents CSRF.
- CSP restricts resource loading sources β the strongest browser-side defense against XSS.
- HSTS forces HTTPS connections β prevents SSL stripping and protocol downgrade attacks.
- HTTP Request Smuggling exploits Content-Length vs Transfer-Encoding header parsing discrepancies between proxy and backend.
- OWASP Top 10 2021: A01 Broken Access Control, A02 Cryptographic Failures, A03 Injection, A08 Software Integrity Failures (Deserialization), A10 SSRF.
- Trust boundary rule: Every injection attack exploits a component trusting user data β validate, sanitize, encode at every trust boundary.
Quick Review & Summary
Use this table to consolidate attack/mitigation mappings before or after the questions above.
| Attack / Concept | OWASP Category | Primary Mitigation |
|---|---|---|
| XSS (Reflected, Stored, DOM) | A03 Injection | Output encoding, CSP, HttpOnly cookies |
| SQL Injection | A03 Injection | Parameterized queries / prepared statements |
| CSRF | A01 Broken Access Control | Anti-CSRF tokens, SameSite=Strict cookie |
| SSRF | A10 SSRF | URL allowlisting, network segmentation, IMDSv2 |
| IDOR | A01 Broken Access Control | Server-side authorization on every data access |
| XXE | A03 Injection | Disable DTD / external entity processing |
| Insecure Deserialization | A08 Software Integrity | Avoid deserializing untrusted data; digital signatures |
| JWT alg:none | A02 Cryptographic Failures | Whitelist accepted algorithms; reject alg:none |
| Clickjacking | A05 Security Misconfiguration | X-Frame-Options: DENY or CSP frame-ancestors |
| Credential Stuffing | A07 Auth Failures | MFA, rate limiting, breached password detection |
Frequently Asked Questions
Q. How many Web Security MCQs are available on this page?
Q. What topics do these Web Security MCQs cover?
Q. Are these MCQs suitable for developer security training and certification exams?
Q. What is the OWASP Top 10 and why is it important?
Q. What is the difference between XSS and CSRF?
Q. What is the difference between Study Mode and Exam Mode?
Q. What is SSRF and why is it so dangerous in cloud environments?
Struggling with some questions? Re-read the full Theory Guide: Web Security