What is CSP?
Content Security PolicyContent Security Policy (CSP) is a crucial HTTP response header that provides a robust layer of defense-in-depth against various types of injection attacks, primarily Cross-Site Scripting (XSS) and clickjacking. By explicitly defining which dynamic resources are permitted to load and execute, CSP fundamentally shifts the web security model from a default-allow stance (where any script can run) to a default-deny stance (where only explicitly trusted scripts can execute).
When properly implemented, a Content Security Policy acts as a strict set of rules enforced by the user's browser. Even if an attacker successfully injects a malicious <script> tag into your application's HTML, the browser will refuse to execute it if the script's origin (or its inline nature) violates the established policy.
The XSS problem CSP solves
To understand the value of CSP, we must examine the mechanics of Cross-Site Scripting (XSS). Historically, web browsers exhibited a critical flaw in trust: they inherently trusted any code delivered alongside a webpage's legitimate content.
If an attacker could inject arbitrary JavaScript into a page—perhaps through an unsanitized comment field (Stored XSS) or a reflected search parameter (Reflected XSS)—the browser would execute that code with the full privileges of the victim's session. This allowed attackers to steal session cookies, harvest CSRF tokens, exfiltrate sensitive data, or perform actions on behalf of the authenticated user.
CSP breaks this attack chain. By providing an explicit whitelist of trusted domains and execution contexts, CSP ensures that even if an attacker injects code, the browser will block its execution. It effectively neuters the payload, turning a critical vulnerability into a harmless string of text.
Full CSP header anatomy with real directive examples
A CSP header consists of a series of directives separated by semicolons. Each directive governs a specific type of resource or behavior.
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com 'nonce-xyz123'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://images.example.com; connect-src 'self' https://api.example.com; frame-src 'none'; report-uri /csp-violation-report-endpoint
In this example, the policy establishes a restrictive baseline, selectively overriding it for specific resource types like scripts, images, and API connections.
Directive-by-directive guide
Understanding individual directives is essential for crafting a policy that is both secure and functional.
default-src
The default-src directive serves as the fallback for most fetch directives (like script-src, style-src, etc.) if they are omitted from the policy. Setting default-src 'none' or default-src 'self' is the cornerstone of a secure policy.
script-src
The script-src directive governs the execution of JavaScript. It is the most critical directive for XSS mitigation. You can specify trusted domains (e.g., https://apis.google.com), nonces (e.g., 'nonce-rAnd0m'), or hashes.
style-src
The style-src directive controls stylesheets. While seemingly less dangerous than scripts, malicious CSS can be used for data exfiltration (e.g., CSS injection to read DOM attributes).
img-src
The img-src directive defines valid sources for images. Restricting image sources helps prevent unauthorized tracking pixels and certain forms of data exfiltration.
connect-src
The connect-src directive restricts the URLs that can be loaded using script interfaces, such as fetch, XHR, WebSockets, and EventSource. This is vital for preventing data exfiltration to attacker-controlled servers.
frame-src
The frame-src directive specifies valid sources for nested browsing contexts (e.g., <iframe>). This is essential for preventing unauthorized framing and clickjacking attacks.
report-uri / report-to
The report-uri (deprecated but widely supported) and report-to (modern standard) directives instruct the browser to send a JSON report to a specified endpoint whenever the policy is violated.
Unsafe directives to avoid: unsafe-inline, unsafe-eval
When crafting a policy, certain keywords severely degrade security.
'unsafe-inline': This allows the execution of inline<script>and<style>blocks. Using this inscript-srccompletely negates CSP's ability to protect against XSS, as an attacker's injected script will be executed.'unsafe-eval': This allows the use ofeval()and similar methods (e.g.,setTimeout(string),new Function()). Attackers frequently use these functions to execute arbitrary payloads constructed at runtime.
While they should be avoided, teams are sometimes forced to use them due to legacy dependencies, poorly written third-party libraries, or deeply ingrained architectural patterns that require inline execution before a proper refactor can occur.
Nonces and hashes as alternatives to unsafe-inline
To execute necessary inline scripts securely without resorting to 'unsafe-inline', CSP provides two robust mechanisms:
- Nonces (Number Used Once): A cryptographically secure random string is generated by the server for each HTTP response. This nonce is included in the CSP header (
script-src 'nonce-random123') and applied to authorized script tags (<script nonce="random123">). Injected scripts lack the correct nonce and are blocked. - Hashes: The server calculates a cryptographic hash (e.g., SHA-256) of the inline script's content. This hash is included in the CSP header (
script-src 'sha256-hashvalue...'). If an attacker alters the script even slightly, the hash will not match, and execution is blocked.
Report-Only mode: how to deploy safely
Deploying a strict CSP directly into enforcement mode on an existing application is virtually guaranteed to break functionality. Legitimate scripts, styles, and integrations will inevitably be blocked.
The solution is Content-Security-Policy-Report-Only. This header instructs the browser to evaluate the policy and report any violations to the designated endpoint, but crucially, it does not block any resources.
Callout: never start with enforcement mode
Important
Never deploy a new CSP directly in enforcement mode on a production application. Always start with Content-Security-Policy-Report-Only to gather telemetry, analyze violations, and iteratively refine the policy before enforcing it.
Nginx and Apache CSP configuration examples
Implementing CSP at the web server level ensures consistent enforcement across all responses.
Nginx:
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'nonce-$request_id'; report-uri /csp-endpoint;" always;
Apache:
Header set Content-Security-Policy "default-src 'self'; script-src 'self'; report-uri /csp-endpoint;"
CSP bypass techniques — why a strong allowlist matters
A poorly configured CSP can provide a false sense of security. Several common bypass techniques exist:
- Open Redirects: If a whitelisted domain contains an open redirect vulnerability, an attacker can use it to load a malicious script from an untrusted origin, bypassing the
script-srcallowlist. - JSONP Endpoints: If a whitelisted domain hosts an insecure JSONP endpoint, an attacker can exploit it to execute arbitrary JavaScript within the context of the trusted application.
These bypasses highlight why relying solely on broad domain allowlists (e.g., script-src https://*.example.com) is dangerous. Strict CSP, relying on nonces or hashes (and strict-dynamic), offers far superior resilience against these bypass techniques.
Testing your CSP
Validating your policy is critical.
- Browser DevTools: The Console tab in Chrome or Firefox Developer Tools will explicitly flag blocked resources and indicate which CSP directive was violated.
- CSP Evaluator Tools: Online tools can statically analyze your policy string, identifying syntax errors, dangerous directives (like
'unsafe-inline'), and known bypasses associated with whitelisted domains.
How CyberFurl Helps
Automated monitoring. Zero manual work.
CyberFurl scans your web properties to detect missing or misconfigured Content Security Policy headers — including dangerous directives like unsafe-inline, unsafe-eval, and wildcard source allowances that defeat XSS protection. The platform provides a CSP violation report aggregation view so you can identify which legitimate resources are blocked before tightening your policy from report-only mode to enforcement.
