Skip to Content

Can you bypass content security policy?

Can you bypass content security policy?

Content Security Policy (CSP) is an added layer of security that helps detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. The policy allows a web application to declare the content sources it expects to load and instructs the browser to only execute or render resources from those sources.

What is Content Security Policy?

Content Security Policy (CSP) is an HTTP header that allows site owners to control resources the browser is allowed to load for a given page. It helps mitigate cross-site scripting (XSS) attacks by telling the browser to only execute scripts loaded from whitelisted domains. Without CSP, the browser will load resources from any location. With CSP, restricted resources won’t load.

CSP works by whitelisting domains and protocols that the browser should trust. For example, if your CSP header only allows scripts from your domain and nowhere else, then there’s no way an attacker can load remote code into your website. This significantly reduces the risk and impact of XSS attacks.

Some key things to know about CSP:

  • CSP is implemented via an HTTP header sent from the server on each request
  • The browser will then only allow resources to load that match the CSP directives
  • There are directives for scripts, stylesheets, images, fonts, frames, media, objects and more
  • CSP entirely prevents whole classes of attacks like XSS, clickjacking, code injection
  • CSP is supported by all major browsers today

Overall, CSP aims to give you granular control over resource loading to prevent injections and defacements. Properly configured, it’s an invaluable security tool for any website.

How does Content Security Policy work?

Here is an overview of how CSP works:

  1. The server sends the CSP HTTP header along with the response.
  2. The client (browser) receives the CSP policy and stores it.
  3. When the page requests a resource (script, stylesheet, image, etc), the browser checks if the resource is allowed by the CSP policy.
  4. If the resource is allowed, it gets loaded normally. If it violates the policy, it does not load.
  5. If a policy violation occurs, the browser sends a CSP violation report to the server.
  6. The server can log and analyze the violations to improve security.

The key steps are that the browser stores the policy, then checks each resource against that policy. Resources that don’t match the whitelist won’t load. This prevents the page from loading malicious assets.

CSP policies can be very flexible. For example, you can whitelist your own domain but disallow all inline scripts. Or whitelist certain CDNs for scripts but not images. The combinations are endless to tightly restrict resource loading.

Benefits of Content Security Policy

Here are some of the main benefits of using Content Security Policy on your website:

  • Mitigate XSS attacks – CSP makes it harder for attackers to inject malicious code.
  • Control resource loading – Fine-grained control over what assets the page can load.
  • Defend against clickjacking – Block framing of your content by other sites.
  • Detect vulnerabilities – CSP violation reports help uncover holes in your defenses.
  • Stay safer by default – CSP blocks unsafe inline scripts, unsafe eval, etc by default.
  • Peace of mind – Know exactly what resources your site needs and lock it down.

In general, CSP forces you to understand exactly what assets and resources your app truly needs to function properly. This leads to tighter security by whitelisting only those required resources.

CSP can be a powerful ally in securing your web applications and preventing entire classes of web vulnerabilities. It’s a defense-in-depth tool that every security-conscious developer should utilize.

How to implement Content Security Policy

Here are the basic steps to implement a Content Security Policy for your site:

  1. Audit resources – Review all the resources loaded by your site – scripts, stylesheets, fonts, etc.
  2. Define policy – Create CSP directives to whitelist approved sources for each resource type.
  3. Set CSP headers – Configure your server to send the CSP HTTP header on each response.
  4. Test policy – Verify the policy works as expected and doesn’t break functionality.
  5. Monitor violations – Check the CSP violation reports for any bugs or policy gaps.
  6. Tighten policy – Gradually tighten the policy by removing unused sources and wildcards.

It’s best to start with a loose policy and tighten it over time as you analyze violation reports. Going too strict initially will likely break site functionality. A gradual and iterative approach allows you to dial in security without impacts.

There are also tools and browser extensions that can analyze your site and generate a recommended starting CSP policy. These can provide a useful blueprint to work from.

Common ways to bypass CSP

Although CSP provides an added layer of security, there are still some ways attackers attempt to bypass CSP protections:

Using incorrect CSP directives

If the CSP policy is overly permissive or uses insecure directives, it can be bypassed. For example, allowing ‘unsafe-inline’ scripts disables protections against XSS. Policies must be carefully configured to avoid insecure options.

Policy injection

An attacker may attempt to inject their own CSP header or use a data URL to inject an unsafe policy. Input validation is key to prevent policy injection vulnerabilities.

Nonces and hashes

CSP nonces and hashes can allow inline scripts in some cases. An attacker may try to guess these values and inject unauthorized scripts. Generating strong unique nonces and hashes per request can mitigate this.

Script gadgets

An attacker constructs valid snippets of JavaScript that when chained together form malicious logic. Validate and sanitize any usage of innerHTML, eval and DOM manipulation to prevent abuse.

Mislabeled content types

Resources can use incorrect Content-Type headers to bypass policies. For example, an XSS payload sent as image/jpeg. Proper Content-Type validation helps prevent mislabeling.

Policy differences in navigation

The page’s CSP may not carry over during a redirect or navigation. An attacker can exploit this to inject content into the new page context. Consistent policies that apply across navigation help mitigate this.

Overall, proper CSP configuration, stripping user-inputs, and validating content types will thwart most bypass attempts. No security solution is perfect, but CSP forces attackers to get far more creative compared to a site with no CSP at all.

Examples of bypassing CSP

Here are some real world examples of ways attackers have attempted to bypass CSP protections on websites:

Abusing the base-uri directive

The base-uri directive can allow reading local files if set improperly. An attacker exploited this on a site with the following policy:

Content-Security-Policy: base-uri 'self';

By including a base tag, the attacker could set base-uri to the local file context and read sensitive files:

<base href="file:///">

This exposed local file contents to the attacker. Properly configured policies must omit dangerous values like ‘self’ for base-uri.

Inline script injection via PDF objects

Attackers abused PDF objects to inject inline JavaScript payloads even on sites with strict CSP policies like:

Content-Security-Policy: default-src 'none'; object-src 'none' 

By embedding a PDF object with a Javascript action, they could execute XSS payloads:

<object data="data:application/pdf;base64,AA...inline_script...AA">

Removing object-src as an allowed source prevents this type of bypass.

Capturing form data via CSP reporting

Attackers have crafted clever CSP bypass techniques by abusing the violation reporting feature itself. By injecting a form that sends data via a reporting endpoint, sensitive form data can be captured:

<form action="javascript:..." onsubmit="fetchReport">
   <input name="creditCard">
   <input type="submit">

Proper input sanitization on the reporting end catches exfiltration through this channel.

These examples illustrate some real ways attackers have managed to circumvent CSP protections. It underscores the importance of analyzing bypass techniques, learning from them and enhancing your policy over time.

Tools for testing CSP bypass

Here are some useful tools for testing CSP bypass techniques:

CSP Evaluator

Burp Suite extension that analyzes CSP headers and automates bypass testing of directives and script injections.

CSP-Bypasser

Python tool to test different CSP bypass methods including script gadgets, hashes, nonces, etc.

csp-auditor

Node.js command line tool that checks for CSP misconfigurations and vulnerable directives.

csp-test

Go library to test CSP headers against different types of payloads and brute force value combinations.

csper

Cross-site scripting assisted by CSP Evaluator for Regression testing. Automates XSS testing against CSP policies.

Combining manual inspection with automated bypass testing helps evaluate the strength of your CSP implementation and identify areas for improvement. A continuous evaluation process is key to staying ahead of new techniques.

Best practices for robust Content Security Policy

Here are some best practices to configure an effective CSP and prevent bypasses:

  • Only allow scripts from trusted sources like your origin and vetted CDNs
  • Completely disallow ‘unsafe-inline’ which nullifies protections
  • Tightly restrict directives like object-src, base-uri, and others
  • Set a secure default-src like ‘none’ or strict origin
  • Strip user inputs before inserting into page or reporting to backend
  • Generate strong unique nonces and hashes per request
  • Validate and sanitize Content-Type headers on resources
  • Enable CSP on every page including during navigation
  • Monitor and analyze violation reports continuously
  • Regularly test your CSP against new bypass techniques

A strong CSP is built through continuous iteration based on testing feedback and learnings from new bypass methods. The policy should be strict by default but evaluated often to enable tuning it over time without introducing breaks.

Conclusion

Content Security Policy is an effective defense-in-depth technique to mitigate certain web vulnerabilities like XSS, code injections and unauthorized resource loads. Although not bulletproof, a well-configured policy dramatically raises the difficulty bar for attackers.

CSP bypasses do exist by abusing misconfigurations, policy differences, script gadgets and other techniques. However, regular evaluation and testing enables uncovering policy gaps and strengthening protections over time.

When implemented following current best practices, CSP can significantly improve the security posture of web applications. Combined with other measures like input validation, output encoding and regular testing, it creates a robust defense against injection attacks.