Web Defense Primitives — headers, cookies, and the threats they map to
Most of these are response headers. Each one defends a specific threat — deploy the wrong one and you have a misconfiguration, not a defense.
The browser security model
- Web-defense primitives are browser-enforced or server-declared mechanisms that constrain what loaded content can do; they are defense-in-depth controls, not substitutes for fixing the underlying bug (e.g. CSP mitigates but does not "fix" XSS).
- This lesson maps primitives to four threat classes: Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), clickjacking / UI redress, and MIME-type confusion (content sniffing) — plus transport downgrade and third-party supply-chain tampering.
- Same-Origin Policy (SOP) is the foundational restriction: scripts from origin A cannot read responses from origin B by default; CORS, CSP, cookies, and the other headers all refine or extend SOP — they do not replace it.
- Each primitive defends a specific threat; deploying the wrong primitive (e.g. CORS to "stop CSRF") is a classic misconfiguration that maps to OWASP A05:2021 Security Misconfiguration.
- Most of these are response headers; the absence or misconfiguration of them is itself the weakness (A05:2021).
Four threat classes — and what actually defends them
Each primitive maps to a specific threat. Pick the wrong control and you have a misconfiguration, not a defense.
Cross-Site Scripting (XSS)
DEFENSE
Contextual output encoding (root fix) + CSP + HttpOnly + nosniff
Cross-Site Request Forgery (CSRF)
DEFENSE
SameSite cookies + synchronizer / double-submit token — NOT CORS
Clickjacking / UI redress
DEFENSE
CSP frame-ancestors (modern); X-Frame-Options (legacy)
MIME-type confusion (sniffing)
DEFENSE
X-Content-Type-Options: nosniff
The primitives
Most are response headers; the rest are cookie attributes and markup. Each one is matched to the threat it defends.
Content-Security-Policy (CSP)
Content-Security-PolicyA response header that declares an allowlist of sources for scripts, styles, frames and more; the browser refuses anything outside the policy.
DEFENDS
XSS (primary mitigation) + clickjacking
- CSP lets a server declare an allowlist of sources for scripts, styles, images, frames, etc.; the browser refuses to load or execute anything outside the policy, mitigating injected-script execution.
- script-src is the XSS-relevant directive: a strict policy removes 'unsafe-inline' and 'unsafe-eval', blocking inline event handlers and injected <script> bodies — this is what turns a reflected or stored injection into a non-executing string.
- Nonce-based CSP: the server emits a per-response random nonce (script-src 'nonce-<random>') and only <script nonce=...> tags matching it run; the nonce must be unpredictable and unique per response or it is bypassable.
- Hash-based CSP: script-src 'sha256-<base64>' allows a specific inline script by its hash without a nonce — useful for static inline scripts.
- 'strict-dynamic' lets a trusted (nonce/hash) script load further scripts it creates, easing adoption of strict CSP on script-heavy apps while still dropping host allowlists.
- frame-ancestors controls who may embed the page in a frame/iframe — this is the modern clickjacking defense (CWE-1021), superseding the legacy X-Frame-Options header (RFC 7034).
- CSP is mitigation, not prevention: output encoding/sanitization still fixes the root XSS; CSP is the second layer. Report-only mode (Content-Security-Policy-Report-Only) allows safe rollout via violation reports.
- Defends ATT&CK Drive-by Compromise (T1189) and JavaScript execution (T1059.007) by constraining attacker-controlled script.
REFERENCES
Output encoding vs sanitization
Output encoding / sanitizationEncoding neutralizes data so it renders as inert text in a specific context; this is the primary XSS defense, with CSP as backup.
DEFENDS
XSS — the real, root-cause fix
- Output encoding (escaping) neutralizes data so it renders as inert text in a specific context; it is the primary XSS defense, with CSP as backup. Mapped to CWE-116 (Improper Encoding or Escaping of Output) and CWE-79.
- Encoding is CONTEXTUAL: HTML body, HTML attribute, JavaScript, URL, and CSS contexts each require different escaping. Using HTML-entity encoding inside a JavaScript or URL context does not stop XSS.
- Sanitization differs from encoding: sanitization removes or rewrites dangerous markup to allow some HTML through (e.g. rich text), and must use a vetted, allowlist-based library (e.g. DOMPurify) — never hand-rolled regex/blocklists.
- Rule of thumb: encode when you want to display untrusted data as text; sanitize only when untrusted HTML must be rendered as markup. Prefer auto-escaping template engines and avoid sinks like innerHTML / dangerouslySetInnerHTML / eval().
- DOM-based XSS lives entirely client-side (data flows from a source like location.hash into a sink); server-side headers do not see it, so safe-sink coding plus Trusted Types is the defense.
REFERENCES
CORS — what it does and does NOT protect
Access-Control-Allow-OriginCORS is a controlled relaxation of the Same-Origin Policy: a server opts in to letting specific other origins READ its responses from script.
DEFENDS
Controls cross-origin reading of a resource (not CSRF)
- Cross-Origin Resource Sharing (CORS) is a controlled RELAXATION of the Same-Origin Policy: via Access-Control-Allow-Origin and related headers a server opts in to letting specific other origins READ its responses from script.
- CORS protects the RESOURCE OWNER's data from being read cross-origin; it is enforced by the browser on the reading side, not a server-side access control.
- Critical misconception: CORS does NOT prevent CSRF. A permissive or absent CORS policy does not stop a forged state-changing request — simple requests (GET/POST form-encoded) are SENT cross-origin regardless; CORS only governs whether the attacker can READ the response.
- Dangerous misconfigurations: reflecting the Origin header into Access-Control-Allow-Origin together with Access-Control-Allow-Credentials: true effectively allows any site to read authenticated responses; using '*' with credentials is blocked by the spec, but reflection bypasses the intent. Maps to CWE-942 (Permissive Cross-domain Policy with Untrusted Domains).
- Preflight (OPTIONS) requests gate "non-simple" requests (custom headers, PUT/DELETE, JSON content-type) — a defense the server can use, but it does not substitute for CSRF tokens or SameSite.
- CORS misconfiguration is an OWASP A05:2021 Security Misconfiguration issue and can lead to A01:2021 Broken Access Control consequences.
REFERENCES
CSRF defenses: SameSite, synchronizer & double-submit tokens
SameSite / anti-CSRF tokenCSRF abuses the browser's automatic cookie attachment to forge authenticated requests; SameSite plus an unguessable token are the defenses.
DEFENDS
Forged authenticated state-changing requests
- CSRF (CWE-352) abuses the browser's automatic attachment of cookies to forge authenticated state-changing requests from an attacker-controlled page. In OWASP Top 10 2021, CSRF is categorized under A01:2021 Broken Access Control.
- The SameSite cookie attribute is the primary modern defense: SameSite=Lax (a common browser default) stops cookies on cross-site subrequests and cross-site POSTs while allowing top-level GET navigation; SameSite=Strict blocks all cross-site sending; SameSite=None requires Secure and re-enables cross-site sending (needed for legitimate cross-site flows).
- SameSite is defense-in-depth, not complete: it does not cover same-site attacks (e.g. a subdomain XSS), older browsers, or "Lax" GET-based state changes — so token-based defenses are still required.
- Synchronizer token pattern (anti-CSRF token): the server issues a per-session (or per-request) unpredictable token, stored server-side, that must accompany state-changing requests; the cross-site attacker cannot read it (SOP) so cannot forge it. This is the strongest CSRF defense.
- Double-submit cookie pattern: the token is sent both as a cookie and as a request parameter/header; the server verifies they match — stateless, but must be hardened (signed/HMAC'd token, "__Host-" cookie prefix) because a same-site/subdomain attacker could otherwise plant the cookie.
- Custom-header check (e.g. require X-Requested-With or a custom header on fetch/XHR) leverages CORS preflight: a cross-origin page cannot set custom headers without a passing preflight, so it is a useful supplementary CSRF defense for JSON APIs.
- Defends against forged authenticated actions; related ATT&CK exposure includes session abuse via Browser Session Hijacking (T1185).
REFERENCES
Cookie flags: HttpOnly and Secure
HttpOnly; SecureHttpOnly hides a cookie from JavaScript so XSS cannot read it; Secure ensures it is only sent over HTTPS.
DEFENDS
Cookie theft via JavaScript and cleartext transport
- The HttpOnly cookie flag makes a cookie inaccessible to document.cookie / JavaScript, so an XSS payload cannot directly read or exfiltrate the session cookie. Absence maps to CWE-1004 (Sensitive Cookie Without 'HttpOnly' Flag).
- The Secure cookie flag ensures the cookie is only sent over HTTPS, preventing leakage over plaintext HTTP. Absence maps to CWE-614 (Sensitive Cookie in HTTPS Session Without 'Secure' Attribute).
- Cookie prefixes harden binding: "__Secure-" requires the Secure flag; "__Host-" additionally forbids Domain and requires Path=/, preventing subdomain cookie-planting attacks relevant to double-submit CSRF.
- HttpOnly defends ATT&CK Steal Web Session Cookie (T1539) against the JavaScript-read vector; it does not stop server-side theft or a full XSS that performs in-page actions, so it pairs with CSP and SameSite.
- Cookies and these attributes are standardized in RFC 6265 (HTTP State Management Mechanism).
REFERENCES
HSTS — HTTP Strict Transport Security
Strict-Transport-SecurityA header telling the browser to only contact the origin over HTTPS, converting any http:// attempt before a request even leaves.
DEFENDS
Transport downgrade / SSL-stripping MITM
- HSTS is the Strict-Transport-Security response header that instructs the browser to only contact the origin over HTTPS for max-age seconds, converting any http:// attempt to https:// before a request leaves the browser.
- It defends against SSL-stripping / transport-downgrade man-in-the-middle attacks and protects cookies/credentials from cleartext exposure — mapped to CWE-319 (Cleartext Transmission of Sensitive Information) and OWASP A02:2021 Cryptographic Failures.
- includeSubDomains extends the policy to all subdomains; the "preload" directive (with a long max-age + includeSubDomains) enables hard-coding the domain into browsers' preload lists so even the first-ever request is forced to HTTPS, closing the trust-on-first-use gap.
- Defends ATT&CK Adversary-in-the-Middle (T1557) by removing the downgradeable plaintext hop.
- HSTS is specified in RFC 6797; NIST SP 800-52 Rev. 2 provides the broader TLS configuration guidance that HSTS complements.
REFERENCES
X-Content-Type-Options and MIME sniffing
X-Content-Type-Options: nosniffnosniff disables browser MIME-type guessing, forcing it to honor the declared Content-Type instead of reinterpreting a response as HTML/JavaScript.
DEFENDS
MIME-type confusion / content sniffing
- X-Content-Type-Options: nosniff disables browser MIME-type sniffing, forcing the browser to honor the declared Content-Type instead of guessing — preventing a response served as text/plain or image from being reinterpreted and executed as HTML/JavaScript.
- Without nosniff, a user-uploaded or attacker-influenced file mis-served with a guessable type can be "sniffed" into an executable type, becoming an XSS / content-injection vector (CWE-79 class outcome) and a content-type confusion misconfiguration (A05:2021).
- nosniff also makes browsers block scripts/styles whose MIME type does not match the request destination, hardening against type confusion in module/style loads.
- The nosniff behavior is defined normatively in the WHATWG Fetch Standard.
REFERENCES
Referrer-Policy and Permissions-Policy
Referrer-Policy; Permissions-PolicyReferrer-Policy limits how much URL leaks in the Referer header; Permissions-Policy shrinks which powerful browser features the page may use.
DEFENDS
Sensitive data leakage & over-broad feature access
- Referrer-Policy controls how much of the URL is sent in the Referer header on outbound navigations/requests; restrictive values such as no-referrer or strict-origin-when-cross-origin prevent leaking sensitive path/query data (tokens, IDs) to third parties — mapped to CWE-200 (Exposure of Sensitive Information).
- strict-origin-when-cross-origin (a common browser default) sends the full URL same-origin, only the origin cross-origin over HTTPS, and nothing on an HTTPS→HTTP downgrade — balancing analytics with leakage prevention.
- Permissions-Policy (formerly Feature-Policy) lets a site allow/deny powerful browser features (camera, microphone, geolocation, payment, fullscreen, etc.) per-origin, shrinking the attack surface a compromised/injected script or embedded iframe can reach.
- Both are A05:2021 Security Misconfiguration controls when absent; they are hardening / least-privilege measures rather than fixes for a specific injection bug.
- Referrer-Policy is a W3C specification; Permissions-Policy is a W3C specification.
REFERENCES
Subresource Integrity (SRI)
integrity="sha384-..."SRI pins a cryptographic hash on a <script> or <link>; the browser refuses to execute the resource if its bytes do not match.
DEFENDS
Third-party / CDN tampering (supply chain)
- SRI lets a page pin a cryptographic hash on a <script> or <link> via the integrity attribute (e.g. integrity="sha384-..."); the browser refuses to execute the resource if its bytes do not match the hash, defeating a tampered/compromised CDN.
- It directly addresses the supply-chain risk of including third-party code without verifying it — mapped to CWE-494 (Download of Code Without Integrity Check) and OWASP A08:2021 Software and Data Integrity Failures.
- SRI requires crossorigin="anonymous" on cross-origin resources so the browser can validate them under CORS; it is most effective on versioned, immutable assets (a hash cannot cover content that legitimately changes).
- SRI complements CSP: CSP says which origins may load scripts, SRI verifies the exact bytes of those scripts — together they defend the Magecart-style compromised-third-party-script attack pattern.
- Subresource Integrity is defined in a W3C Recommendation.
REFERENCES
Common misconceptions
What these primitives do NOT do — the mistakes that turn a control into a false sense of security.
CLAIM
"CORS stops CSRF."
REALITY
No. A forged simple request (GET/POST form-encoded) is still SENT cross-origin; CORS only governs whether the attacker can READ the response. Use SameSite + tokens for CSRF.
CLAIM
"CSP fixes XSS."
REALITY
No. CSP mitigates injected-script execution as a second layer; contextual output encoding/sanitization is the root fix. Deploy both.
CLAIM
"HTML-escaping everywhere is enough."
REALITY
No. Encoding is contextual — HTML-entity encoding inside a JavaScript, URL, or CSS context does not stop XSS. Encode for the exact sink context.
CLAIM
"SameSite=Lax alone stops all CSRF."
REALITY
No. It misses same-site/subdomain attacks, older browsers, and GET-based state changes. Pair it with a synchronizer or hardened double-submit token.
CLAIM
"HttpOnly makes XSS harmless."
REALITY
No. It only blocks the JavaScript cookie-read vector. A full XSS can still perform in-page actions; HttpOnly pairs with CSP and SameSite.
CLAIM
"Reflecting Origin into the CORS header is fine."
REALITY
No. Reflecting Origin with Access-Control-Allow-Credentials: true lets any site read authenticated responses (CWE-942). Use a strict allowlist.
Threat-to-primitive map
A summary: each threat, its identifiers, and the primitive(s) that defend it.
| Threat | Identifiers | Defenses |
|---|---|---|
Cross-Site Scripting (XSS) | CWE-79 A03:2021 | Contextual output encoding/sanitization (root fix, CWE-116) + Content-Security-Policy (script-src, nonce/hash, strict-dynamic) + HttpOnly cookie (CWE-1004) + X-Content-Type-Options: nosniff. |
Cross-Site Request Forgery (CSRF) | CWE-352 A01:2021 | SameSite=Lax/Strict cookies + synchronizer token or hardened double-submit token + custom-header/preflight check. NOT CORS. |
Clickjacking / UI redress | CWE-1021 | CSP frame-ancestors (modern); X-Frame-Options (legacy, RFC 7034). |
MIME-type confusion | A05:2021 | X-Content-Type-Options: nosniff (WHATWG Fetch). |
Transport downgrade / MITM | CWE-319 A02:2021 T1557 | HSTS (RFC 6797) with includeSubDomains + preload. |
Cross-origin data read | CWE-942 | Correctly scoped CORS (Fetch). Remember a reflected-Origin + credentials policy is dangerous. CORS does not stop CSRF. |
Third-party / CDN tampering | CWE-494 A08:2021 | Subresource Integrity + CSP allowlist. |
Data leakage via referrer / over-broad features | CWE-200 A05:2021 | Referrer-Policy (CWE-200) + Permissions-Policy. Missing security headers in general = A05:2021 Security Misconfiguration. |