The Content-Security-Policy (CSP) is an HTTP header that allows web site owners to control which resources a web page is allowed to load. It helps prevent cross-site scripting attacks and data injection attacks by whitelisting trusted sources of content for a web page. The CSP header defines the content sources a browser is allowed to load for that specific page, allowing fine-grained control over where resources like scripts, stylesheets, images, and more can be loaded from.
How Does CSP Work?
The CSP header consists of directives that whitelist sources of content for various resource types. For example, the “script-src” directive controls which sources scripts can be loaded from, while “style-src” controls stylesheets. Some common CSP directives include:
- script-src – defines valid sources for JavaScript
- style-src – defines valid sources for stylesheets
- img-src – defines valid sources of images
- connect-src – defines valid endpoints for XMLHttpRequest, WebSocket, and EventSource
- font-src – defines valid sources for fonts
- object-src – defines valid sources for plugins
- media-src – defines valid sources for audio and video
Each directive expects a whitelist of sources, like domains, IP addresses, content delivery networks (CDNs), and hashes. For example:
Content-Security-Policy: script-src 'self' cdn.example.com; style-src 'self';
This policy only allows scripts to be loaded from the current origin and cdn.example.com, while only allowing stylesheets from the current origin. Leaving a directive empty effectively blocks that resource type.
CSP also supports keywords like ‘self’ for the current origin, ‘none’ to disable a resource type, and ‘unsafe-inline’ to allow inline code like JavaScript event handlers. Hashes can whitelist specific inline scripts and styles by generating a hash of the content.
How to Check a URL’s CSP
There are a few methods to check the Content-Security-Policy of a specific URL:
Browser Developer Tools
Most modern browsers include developer tools that let you inspect the HTTP headers of a web page. For example, in Chrome:
- Open the URL in Chrome
- Right click and select Inspect
- Go to the Network tab
- Reload the page
- Click on the URL in the list of network requests
- Switch to the Headers tab
- Look for the Content-Security-Policy header
The CSP header and policy will be shown for that URL here. Other browsers like Firefox also provide similar inspection of HTTP response headers.
cURL Command
The cURL command line tool can also be used to view a URL’s HTTP headers including CSP. For example:
curl -I https://example.com
The -I flag displays only the HTTP response headers for that URL. This will show the CSP header if the site has one enabled.
Online CSP Checker Tools
There are also a number of online tools and APIs that can check a URL’s CSP policy:
- CSP Evaluator – Checks CSP and provides feedback
- Report URI Tools – Analyze headers including CSP
- CSP Scanner – Checks CSP directives and validity
- Security Headers – Analyzes all security headers including CSP
These tools simply take a URL and return details about any enabled CSP policy, directive values, and validity.
Bypassing CSP
While CSP aims to lock down a web page’s content sources, there are still some methods attackers have found to potentially bypass CSP restrictions:
Script Gadgets
Most CSP policies still allow inline JavaScript events and handlers like onclick
. Attackers can chain together multiple benign-looking inline scripts to form “gadgets” that can exfiltrate data or redirect the page.
Vulnerable JavaScript Libraries
Some third-party JavaScript libraries can be vulnerable to code injection even when loaded from a trusted CDN. If those scripts are whitelisted, an attacker may be able to inject arbitrary code.
Incorrect Implementations
Mistakes in CSP policies like failing to use 'strict-dynamic'
mode, overbroad wildcards, or trusting too many CDNs can weaken the policy’s protections.
Nonces
CSP nonces that whitelist inline scripts are intended for one-time use but can sometimes be reused to inject arbitrary script payloads.
While not perfectly bulletproof, CSP aims to significantly raise the difficulty bar for content injection attacks when implemented correctly using the latest browser security features.
Benefits of CSP
Here are some of the key benefits of using CSP:
Prevents Code Injection
By whitelisting all script and content sources, CSP can prevent unauthorized third-party code from being injected into a site. This helps block XSS and data injection attacks.
Defends Against Data Leaks
CSP can be used to tightly restrict what endpoints data like XMLHttpRequests and fetches can be sent to, reducing data exfiltration risks.
Safer Third Party Content
Properly vetting and whitelisting third party APIs, widgets, ads, and content reduces the risks of supply chain attacks through trusted third-party domains.
Improves Performance
CSP minimizes the need for extra security controls like excessive input sanitization by preventing unauthorized resources from loading in the first place.
Helps Adopt Security Best Practices
Creating and maintaining a strict CSP policy encourages better discipline around only allowing trusted origins and minimizing use of unsafe inline code.
CSP Limitations
CSP is not a silver bullet and has some limitations to be aware of:
Not Full Attack Coverage
CSP mainly protects against code injection and unauthorized content loading. Other attack vectors like XSS filter bypasses, CSRF, and UI redressing may still be possible.
Requires Additional Effort
Crafting a strong and effective CSP policy requires auditing all resource usage and sources across an entire site, which can be challenging at scale.
Can Break Functionality
Overly strict policies can block embedded widgets, ads, and other legitimate content from loading and break site functionality.
Bypass Techniques Exist
As mentioned earlier, some methods like script gadgets and nonce reuse can bypass CSP restrictions under certain conditions.
Browser Support Issues
While CSP is widely supported in modern browsers, partial support or buggy implementations may impact security guarantees.
CSP is most effective as part of a defense-in-depth approach combined with other protections.
CSP Deployment Tips
Here are some best practices for deploying an effective Content-Security-Policy:
- Audit existing content sources and prune any unnecessary domains
- Eliminate inline scripts and event handlers if possible
- Specify a CSP in report-only mode first to identify violations
- Set a strict default-src directive like ‘self’ as the fallback
- Use nonces or hashes to whitelist necessary inline scripts
- Set the Content-Security-Policy-Report-Only header initially
- Fix any CSP violations before deploying full enforcement
- Only whitelist current and essential content delivery networks
- Preload key scripts using the
script-src
directive - Enable the
strict-dynamic
source expression
Testing in report-only mode and fixing violations is key before fully enforcing a strict CSP policy.
Conclusion
The Content-Security-Policy HTTP header is an effective way to restrict unauthorized content sources and help defend against code injection attacks. When properly configured, CSP can significantly improve a site’s security posture by whitelisting only trusted domains and disabling unsafe practices like inline scripts.
However, CSP is not a silver bullet and still has some bypasses and implementation challenges. Deploying an effective policy requires carefully auditing and specifying content sources across an entire site. CSP is most powerful when combined with other modern security headers as part of an overall defense-in-depth strategy.