What is Content Security Policy (CSP)
Content Security Policy (CSP) is a browser security standard developed by the W3C
to help web developers reduce the risk of certain types of attacks, such as XSS and
data injection attacks. CSP achieves this by allowing website administrators to define
where content (scripts, styles, images, etc.) can load from, enforcing a "content
loading whitelist." This restricts malicious code from being injected and executed in
user sessions.
CSP policies are configured via HTTP headers (or meta tags, though headers are
recommended), with granular control over what is allowed to load on a page, helping
to safeguard users from harmful code.
Why CSP is Essential/Needed
CSP provides a powerful way to prevent vulnerabilities. XSS attacks, for instance, occur when an attacker injects malicious code into a website, which then executes in the user's browser. CSP addresses this by enabling developers to control which scripts and other resources can load, effectively limiting or preventing this attack vector.
How CSP Works?
CSP works by applying restrictive directives via an HTTP header, primarily Content-Security-Policy, that specifies permitted sources for various resource types. When a browser supporting CSP encounters this header, it enforces restrictions based on the provided directives. If a resource does not comply, it is blocked from loading.
Key CSP Directives
Each CSP directive controls specific types of content and enforces policies for that type. Here are some critical directives:
1. default-src: Acts as a fallback for all other resource types if a more specific directive is not defined.
default-src 'self';
2. script-src: Defines sources allowed for JavaScript files. Crucial for mitigating XSS risks.
script-src 'self' https://trusted-scripts.com;
3. style-src: Specifies sources for stylesheets.
style-src 'self' https://trusted-styles.com;
4. img-src: Controls allowed image sources.
img-src 'self' https://images.example.com;
5. font-src: Controls which fonts can be loaded.
font-src 'self' https://fonts.example.com;
6. connect-src: Defines sources allowed for network requests like AJAX, WebSockets, etc.
connect-src 'self' https://api.example.com;
7. object-src: Defines where `<object>`, `<embed>`, and `<applet>` elements can load from, often used to restrict plugins and applets.
object-src 'none';
8. frame-ancestors: Controls which sources are permitted to embed the page in an iframe, helping to prevent clickjacking.
frame-ancestors 'self';
9. form-action: Restricts where forms can submit data.
form-action 'self';
10. sandbox: Adds a layer of restrictions to content, like preventing scripts or forms.
sandbox;
Reporting CSP Violations
CSP supports violation reporting with report-uri or report-to directives, which send reports to a specified URI when a violation occurs. These reports contain details about the blocked content, helping developers refine policies.
Example:
Content-Security-Policy: default-src 'self'; report-uri https://your-domain.com/csp-report;
CSP Bypass Techniques
While CSP is effective, certain misconfigurations or oversights can allow attackers to bypass it. Here are some common CSP bypass techniques and how they work:
1. Weak or Relaxed Policies
- Allowing unsafe-inline or unsafe-eval weakens CSP, making it easier for attackers to execute injected scripts or unsafe functions.
- Allowing broad origins (e.g., script-src *) increases the attack surface, as it permits loading scripts from untrusted domains.
2. Nonce and Hash Reuse
- Nonces ('nonce-<value>') and hashes ('sha256-<hash>') are effective for allowing only specific inline scripts but reusing them across pages can enable attackers to inject scripts by using the same nonce.
- Example
<script nonce="<nonce-value>">alert('Nonce Reuse Bypass');</script>
3. DOM-Based CSP Bypass
- Dynamically creating and injecting elements like <script> or <iframe> can lead to bypasses if the policy allows broad sources (e.g., data: URLs) or if the attacker can control the content being injected.
- Example:
<script>document.write('<img src="x" onerror="alert(\'DOM-based CSP bypass\')">');</script>
4. JSONP and Open Redirects:
- JSONP responses can be exploited within script-src, as attackers can inject scripts via callback functions.
- Open redirects on trusted domains can be abused to load malicious scripts indirectly.
- Example for JSONP:
<script src="https://trusted-jsonp-source.com/callback?callback=alert('JSONP XSS')"></script>
5. Self-XSS:
- A misconfigured CSP that allows self can be exploited by tricking users into executing malicious code in their console.
- Example:
javascript:alert('Self-XSS CSP Bypass');
6. Data URI and Base64 Encoding:
- Permitting data: or blob: URIs can be dangerous, as these can be used to encode scripts that may bypass certain CSP protections if permitted within directives like img-src or media-src .
- Example Payload:
<img src="data:image/svg+xml;base64,PHN2ZyBvbkVycm9yPSJhbGVydCgnRGlnaXRhbCBDU1AgQnlwYXNzJyk7Ij4=">
7. CORS Misconfigurations:
- Misconfigured CORS policies (Access-Control-Allow-Origin: *) can lead to indirect CSP bypasses by enabling attackers to load restricted resources or make unauthorised requests.
8. Header Injection:
- If an attacker can inject custom CSP headers, they may relax the policy, allowing previously blocked resources to load.
Best Practices for CSP Implementation
To minimise the risks of CSP bypass, follow these best practices:
1. Avoid unsafe-inline & unsafe-eval : These weaken your CSP, making XSS and other script-based attacks easier to execute.
2. Implement Unique Nonces per Request: Avoid reusing nonces to ensure that injected scripts cannot exploit a previously-used nonce.
3. Strictly Define Source Origins: Avoid broad policies like `*`, `data:`, or `blob:` URIs unless absolutely necessary. Specify exact, trusted domains.
4. Use Reporting to Monitor Violations: Implement `report-uri` or `report-to` to monitor and review CSP violations. These reports provide insights into potential configuration issues or attack attempts.
5. Regularly Review Dependencies: Keep an eye on third-party scripts and libraries that are allowed by your CSP, and remove any that are no longer needed.
6. Restrict CORS Access: Ensure that CORS configurations are not overly permissive, as attackers can exploit weak CORS to bypass CSP.
Content Security Policy (CSP) is a powerful tool for web security, enabling developers to restrict content loading from untrusted sources. However, CSP’s effectiveness depends on a well-thought-out configuration and strict policies. By implementing secure directives, avoiding dangerous settings like `unsafe-inline`, and regularly monitoring for CSP violations, developers can significantly enhance their site’s security.
Comments