Web Application Security (OWASP Top 10: SQLi, XSS, CSRF, SSRF & Secure Coding)

Advanced web and API application security: the complete OWASP Top 10 (A01–A10), SQL Injection and parameterized queries, Cross-Site Scripting (XSS) and CSP, CSRF and SameSite cookies, SSRF and AWS IMDSv2, XXE, Insecure Deserialization, JWT attacks, CORS, HTTP security headers, and SAST/DAST/IAST/SCA/SBOM.

Level
advanced
Languages
en → en
Cards
32
Markdown
Web Application Security (OWASP Top 10: SQLi, XSS, CSRF, SSRF & Secure Coding) (.md)

Flashcards (32)

#Front (Term / Question)Back (Definition / Answer)ExampleMultiple-Choice Options
1Why do Prepared Statements (Parameterized Queries) completely prevent SQL Injection, whereas input blacklisting or escaping often fails?In a Prepared Statement (`SELECT * FROM users WHERE username = ?`), the database compiles the SQL query structure and execution plan BEFORE inserting parameters. User input is bound strictly as a literal scalar value in a separate protocol phase and can never be interpreted as executable SQL syntax (`OR 1=1--`), even if it contains quotes or SQL keywords. Note: Dynamic table/column names (`ORDER BY`) cannot be parameterized and require strict server-side allowlists.
2Explain Insecure Deserialization (e.g., Java `ObjectInputStream`, Python `pickle`, PHP `unserialize`) and Property-Oriented Programming (POP) gadget chains.When an application deserializes untrusted binary or structured data, the runtime instantiates objects and invokes magic/lifecycle methods (`readObject()`, `__wakeup()`, `__destruct()`, `__reduce__()`) BEFORE type validation occurs. Attackers construct 'gadget chains' of existing classes on the application's classpath to achieve Remote Code Execution (RCE). Mitigation: Never deserialize untrusted data with native object serializers; use safe data-only formats (JSON/Protobuf) with strict schema validation and HMAC signatures.
3What are HTTP Request Smuggling (`CL.TE` / `TE.CL`) and Open Redirect vulnerabilities?HTTP Request Smuggling exploits parsing discrepancies between a front-end reverse proxy/CDN and a back-end HTTP/1.1 server regarding where one request ends and the next begins (by sending conflicting `Content-Length` and `Transfer-Encoding: chunked` headers), poisoning the TCP connection pool and hijacking other users' requests. Open Redirect (`?next=https://evil.com`) redirects users to untrusted external URLs, facilitating phishing and OAuth token theft.
4Compare Stored (Persistent), Reflected (Non-Persistent), and DOM-Based Cross-Site Scripting (XSS).Stored XSS: Malicious script is saved permanently in the backend database (e.g., forum comment or user profile) and executed in the browser of every user who views that page. Reflected XSS: Payload is part of the crafted URL/request (e.g., `?q=<script>...`) and immediately reflected by the server in the HTML response. DOM-Based XSS: Vulnerability exists entirely in client-side JavaScript that reads an untrusted source (`location.hash`, `location.search`) and writes it to a dangerous sink (`innerHTML`, `eval()`, `document.write`) without server involvement.
5What is an Insecure Direct Object Reference (IDOR / BOLA under OWASP A01), and why doesn't replacing sequential integers with UUIDs fix it?IDOR (or Broken Object Level Authorization in APIs) occurs when an application uses user-supplied identifiers (e.g., `/api/invoices/1042` or `?user_id=505`) to fetch database records without verifying on the server that the authenticated user owns or is authorized to access that specific object. UUIDs only obscure the ID (security by obscurity); true remediation requires server-side object-level authorization checks on every request.
6What is Server-Side Template Injection (SSTI) and Prototype Pollution?SSTI occurs when user input is concatenated directly into a server-side template string (e.g., Jinja2, Twig, Freemarker `render_template_string("Hello " + name)`) instead of passed as a context variable; injecting `{{7*7}}` evaluates to `49` and allows traversing Python/Java object hierarchies to RCE. Prototype Pollution (JavaScript/Node.js) occurs when recursively merging untrusted JSON containing `__proto__` or `constructor.prototype`, injecting properties into the base `Object.prototype` across the entire runtime.
7Compare In-Band (Union-Based, Error-Based), Inferential (Boolean-Blind, Time-Based Blind), and Out-of-Band SQL Injection (SQLi).In-Band: Results return directly in the HTTP response via `UNION SELECT` column appending or verbose database error messages. Blind (Inferential): App returns no data/errors; attacker infers truth bit-by-bit via page changes (`AND SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a'`) or response delays (`SLEEP(5)`, `WAITFOR DELAY`). Out-of-Band: Forces the DB server to make an external DNS or HTTP request (`xp_dirtree`, `UTL_HTTP`) carrying exfiltrated data.
8How does Directory Traversal (Path Traversal `../`) differ from Local File Inclusion (LFI) and Remote File Inclusion (RFI)?Path Traversal (`../../../../etc/passwd` or URL-encoded `%2e%2e%2f`) manipulates file path parameters to read arbitrary files outside the web root. LFI additionally passes the local file to an interpreter (e.g., PHP `include()`), executing code if the attacker poisoned `/var/log/apache2/access.log` with a web shell. RFI fetches and executes a script hosted on an external attacker server. Mitigation: Avoid passing user filenames to filesystem APIs; validate against a strict allowlist and canonicalize paths (`realpath`).
9Why does naive IP blocklisting (`127.0.0.1`, `169.254.169.254`, `10.0.0.0/8`) fail to stop SSRF, and what is the proper remediation?Attackers bypass naive SSRF regex/blocklists using DNS Rebinding (domain resolves to a public IP during validation, then immediately rebinds with TTL=0 to `127.0.0.1` during the actual HTTP fetch), HTTP 302 redirects, octal/hex/decimal IP encodings (`0x7f000001`, `2130706433`), IPv6 mapped addresses (`[::ffff:127.0.0.1]`), or URL parser discrepancies. Proper remediation: strict domain allowlists, resolving DNS once and pinning the validated IP in the custom HTTP transport socket, disabling redirects, and running fetchers in an isolated egress-filtered network namespace.
10What are File Upload vulnerabilities, and what is the complete checklist for secure file upload handling?Attackers upload web shells (`.php`, `.jsp`, `.aspx`), polyglot files, SVG files containing Stored XSS, or zip bombs. Secure handling: 1. Validate file extension against a strict allowlist AND verify magic bytes/content (not just client `Content-Type`); 2. Generate a random UUID filename (stripping user path characters); 3. Store files on an isolated external object store (e.g., S3 bucket) or non-executable directory outside the web root; 4. Serve downloads from a separate sandbox domain (`usercontent.example.com`) with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`.
11What is Threat Modeling in OWASP A04 (Insecure Design), and what does the STRIDE mnemonic stand for?Threat Modeling is performed during architectural design before writing code (identifying trust boundaries, data flow diagrams, and abuse cases). STRIDE categorizes six threat types paired with their violated security properties: Spoofing (Authentication), Tampering (Integrity), Repudiation (Non-Repudiation), Information Disclosure (Confidentiality), Denial of Service (Availability), and Elevation of Privilege (Authorization).
12Why is returning `Access-Control-Allow-Origin: null` with `Access-Control-Allow-Credentials: true` a severe CORS vulnerability?Developers sometimes allow `Origin: null` thinking it only applies to local files (`file://`). However, any attacker on the internet can generate a cross-origin request with `Origin: null` simply by placing their exploit JavaScript inside a sandboxed iframe (`<iframe sandbox="allow-scripts allow-forms" srcdoc="...">`). The browser sends `Origin: null` with session cookies attached, allowing the attacker to read authenticated responses.
13Compare Black-Box, White-Box (Clear-Box), and Gray-Box Penetration Testing, and define Rules of Engagement (RoE).Black-Box (Unknown Environment): Tester has zero prior internal knowledge, simulating an external unprivileged attacker (realistic, but time-consuming). White-Box (Known Environment): Tester receives full source code, architecture diagrams, and credentials for maximum vulnerability coverage. Gray-Box (Partially Known): Tester receives standard user credentials/API docs to simulate an insider or compromised user efficiently. Rules of Engagement (RoE) legally define in-scope IP ranges, prohibited techniques (e.g., DoS), testing windows, emergency contacts, and authorization ('Get Out of Jail Free' letter).
14What are the three parts of a JSON Web Token (JWT), and how do the `alg: none` and RS256-to-HS256 Key Confusion attacks work?A JWT consists of `Header.Payload.Signature` (Base64URL-encoded). Note that standard JWTs (JWS) are SIGNED, NOT encrypted (anyone can decode the payload). In `alg: none`, an attacker sets `'alg': 'none'`, modifies `'role': 'admin'`, strips the signature, and poorly configured libraries accept it as valid. In RS256-to-HS256 Key Confusion, the server expects asymmetric RS256 (verifying with its public key), but the attacker switches the header to symmetric `HS256` and signs the token using the server's publicly available RSA Public Key as the HMAC secret!
15What are GraphQL-specific security vulnerabilities, and how are they mitigated?GraphQL exposes a single endpoint allowing clients to specify complex nested queries. Key risks: 1. Introspection enabled in production (`__schema` leaking the entire API schema); 2. Nested Circular Query DoS (e.g., `author { posts { author { posts ... } } }` exhausting CPU/DB); 3. Batching/Aliasing brute-force attacks bypassing rate limits; 4. BOLA/Field-level authorization bypass. Mitigations: Disable introspection in prod, enforce maximum query depth/complexity limits, and validate authorization inside every field resolver.
16Compare SAST, DAST, IAST, and RASP in the Secure Software Development Lifecycle (DevSecOps).SAST (Static Application Security Testing): White-box analysis scanning source code, bytecode, or binaries at rest for tainted data flows without running the app (early shift-left, higher false positives). DAST (Dynamic AST): Black-box scanner probing a running application from the outside via HTTP payloads (finds runtime/config flaws, cannot see source line numbers). IAST (Interactive AST): Instruments the running app via an internal agent during QA tests to combine code visibility with runtime context. RASP: Runtime agent blocking attacks in production.
17What is OWASP A08 (Software and Data Integrity Failures), and how do CI/CD pipeline hardening, SLSA, and Subresource Integrity (SRI) address it?A08 covers untrusted software updates, insecure CI/CD pipelines, and unverified serialized data. SLSA (Supply-chain Levels for Software Artifacts) enforces tamper-proof build provenance and cryptographic code signing (Sigstore/Cosign). Subresource Integrity (SRI) protects web apps loading scripts from third-party CDNs by adding an `integrity="sha384-..."` cryptographic hash attribute to `<script>` tags so the browser refuses to execute a tampered CDN file.
18What is Cache Poisoning (Web Cache Poisoning) vs Web Cache Deception?Web Cache Poisoning: An attacker sends a request containing an unkeyed input (such as an `X-Forwarded-Host` header) that causes the backend to generate a malicious response (e.g., loading scripts from `evil.com`), which the CDN caches and serves to all subsequent visitors. Web Cache Deception: An attacker tricks a logged-in victim into visiting `https://bank.com/account/profile/nonexistent.css`; the origin ignores the `.css` suffix and returns the victim's private profile HTML, which the CDN caches publicly because of the `.css` extension.
19Explain the Browser Same-Origin Policy (SOP) and how dangerous CORS misconfigurations (`Access-Control-Allow-Origin`) leak sensitive data.SOP defines an Origin by the exact tuple `(scheme, hostname, port)`: scripts on `https://evil.com` can generally send requests to `https://api.bank.com`, but SOP blocks `evil.com` from READING the response unless allowed by Cross-Origin Resource Sharing (CORS) headers. If a server dynamically reflects any `Origin` header into `Access-Control-Allow-Origin: https://evil.com` paired with `Access-Control-Allow-Credentials: true`, an attacker website can make authenticated `fetch(..., {credentials: 'include'})` requests and steal the user's private API responses.
20What are the two primary defenses against CSRF: Synchronizer Anti-CSRF Tokens and `SameSite` Cookie attributes?1. Anti-CSRF Tokens (Synchronizer Token Pattern): The server generates a cryptographically random, user-session-bound token placed in a hidden form field or custom HTTP header (`X-CSRF-Token`); because of the Same-Origin Policy, `evil.com` cannot read the token from `bank.com`. 2. `SameSite` Cookie attribute: `SameSite=Strict` never sends the cookie on cross-site requests; `SameSite=Lax` (modern browser default)withholds the cookie on cross-site `POST`/subresource requests while allowing top-level safe `GET` navigation.
21How should a backend server securely validate a JWT?1. Explicitly hardcode/allowlist the expected cryptographic algorithm (`RS256` or `ES256`) in the verification call—never trust the JWT header's `alg` or unverified `jku`/`x5u`/`kid` header paths; 2. Verify the cryptographic signature against the trusted key; 3. Validate standard claims: `iss` (issuer), `aud` (audience—preventing cross-service token replay), `exp` (expiration), and `nbf` (not before); 4. Use high-entropy secrets (>=256 bits) if using HS256.
22What is the primary defense against XSS, and how does Content Security Policy (CSP) provide defense-in-depth?Primary defense: Context-Aware Output Encoding (HTML entity encoding `<` to `&lt;` in HTML body, attribute encoding, JavaScript hex encoding) and using safe DOM APIs (`textContent` instead of `innerHTML`) or auto-escaping frameworks (React/Angular) + `DOMPurify` for rich HTML. Defense-in-depth: HTTP `Content-Security-Policy` header (e.g., `script-src 'nonce-rAnd0m' 'strict-dynamic'; object-src 'none'`) blocks inline scripts, `eval()`, and unauthorized external script domains.
23How does a Cross-Site Request Forgery (CSRF / XSRF) attack work, and why doesn't `HttpOnly` on session cookies prevent it?In CSRF, a victim already logged into `bank.com` visits an attacker's site (`evil.com`), which triggers an automatic cross-origin HTTP request (e.g., a hidden auto-submitting `<form action="https://bank.com/transfer" method="POST">`). Because the browser automatically attaches `bank.com` cookies to requests destined for `bank.com`, the server processes the forged transfer. `HttpOnly` only stops JavaScript from reading the cookie via `document.cookie`; the browser still sends the cookie automatically!
24What is Clickjacking (UI Redressing), and which two HTTP headers prevent a page from being framed by an attacker?In Clickjacking, an attacker loads a legitimate target page inside a transparent `<iframe style="opacity:0">` overlaid directly atop a decoy button on the attacker's site, tricking the user into clicking hidden buttons (e.g., 'Delete Account' or 'Grant OAuth Access'). Defenses: `Content-Security-Policy: frame-ancestors 'none'` (or `'self'`, the modern flexible standard) and the legacy header `X-Frame-Options: DENY` (or `SAMEORIGIN`).
25What are OS Command Injection and LDAP/NoSQL Injection, and how are they prevented?OS Command Injection occurs when user input is concatenated into a shell string (e.g., `system("ping -c 4 " + ip)`), allowing metacharacters (`;`, `&&`, `|`, `$()`) to execute arbitrary OS commands; prevent by calling safe language APIs (`execve`/`subprocess.run(["ping", ip], shell=False)`) that bypass the shell. NoSQL Injection injects operator objects (e.g., MongoDB `{"$ne": null}` in JSON login bodies) to bypass auth; prevent via strict schema/type validation.
26How does Server-Side Request Forgery (SSRF, OWASP A10) exploit cloud environments via `169.254.169.254`, and how does AWS IMDSv2 mitigate it?SSRF tricks a backend server into making HTTP requests to internal-only addresses (e.g., via a webhook or PDF URL fetcher). In cloud environments, requesting `http://169.254.169.254/latest/meta-data/iam/security-credentials/` on IMDSv1 via a simple `GET` returns temporary IAM role credentials. AWS IMDSv2 mitigates SSRF by requiring a session-oriented `PUT` request first with a custom `X-aws-ec2-metadata-token-ttl-seconds` header (and IP TTL=1 to block container routing) to obtain a token.
27Compare SCA (Software Composition Analysis) and SBOM (Software Bill of Materials: CycloneDX & SPDX).While SAST analyzes first-party code written by your developers, SCA scans third-party and open-source dependencies (`package-lock.json`, `pom.xml`, `go.mod`, container layers) against vulnerability databases (NVD, OSV) and license compliance rules. An SBOM (standardized in CycloneDX or SPDX format) is a formal, machine-readable inventory of all software components, transitive libraries, versions, and hashes comprising an application— enabling instant impact assessment when a new CVE (like Log4Shell) drops.
28What is XML External Entity (XXE) Injection, and how do you remediate it?XXE exploits XML parsers that evaluate custom Document Type Definitions (`<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>`), allowing attackers to read local files, trigger SSRF, or cause Billion Laughs (XML bomb) Denial of Service via recursive entity expansion. Remediation: Explicitly disable DTDs (`disallow-doctype-decl`) and external general/parameter entities in the XML parser configuration, or use JSON.
29What is PASTA (Process for Attack Simulation and Threat Analysis) vs DREAD vs Attack Trees?PASTA is a 7-stage, risk-centric threat modeling methodology aligning business objectives with technical threat intelligence and simulated attack paths. Attack Trees decompose a high-level adversary goal (root node, e.g., 'Exfiltrate Customer DB') into boolean `AND`/`OR` sub-goals (leaf nodes). DREAD is a legacy risk-ranking rubric evaluating Damage, Reproducibility, Exploitability, Affected users, and Discoverability.
30Explain the purpose of the HTTP security headers `Strict-Transport-Security` (HSTS), `X-Content-Type-Options`, `Referrer-Policy`, and `Permissions-Policy`.`Strict-Transport-Security: max-age=31536000; includeSubDomains; preload` forces browsers to connect exclusively over HTTPS (preventing SSL-stripping MitM attacks, surtout with HSTS Preload list). `X-Content-Type-Options: nosniff` prevents browsers from MIME-sniffing a non-executable upload (like `image/png`) into executable `text/html` or JavaScript. `Referrer-Policy: strict-origin-when-cross-origin` prevents leaking sensitive URL query paths in the `Referer` header. `Permissions-Policy` restricts browser APIs like camera, microphone, and geolocation.
31Compare Horizontal Privilege Escalation, Vertical Privilege Escalation, and Mass Assignment (Object Injection) in web APIs.Horizontal Privilege Escalation: Accessing resources belonging to another user at the same permission level (e.g., User A viewing User B's medical record). Vertical Privilege Escalation: A standard user executing administrative functions (e.g., calling `/admin/deleteUser`). Mass Assignment: Automatically binding raw JSON request body fields directly to internal data models/ORM entities, allowing an attacker to inject `{"role": "admin", "is_verified": true}`—mitigated by strict allowlist DTOs.
32List all 10 categories of the OWASP Top 10 (2021 edition) in order from A01 to A10.A01: Broken Access Control; A02: Cryptographic Failures; A03: Injection; A04: Insecure Design; A05: Security Misconfiguration; A06: Vulnerable and Outdated Components; A07: Identification and Authentication Failures; A08: Software and Data Integrity Failures; A09: Security Logging and Monitoring Failures; A10: Server-Side Request Forgery (SSRF).