XSS prevention through Content Security Policy

Yes, CSP goes a long way to defending against XSS. If you do a Google search on "Content Security Policy XSS" the first few links explain how and why.

If you're having trouble using Google, here are some good links to help explain how CSP defends against XSS:

  • An Introduction to Content Security Policy from Mike West

  • An Introduction to Content Security Policy from David Müller

  • Using Content Security Policy to Prevent Cross-Site Scripting (XSS) - SendSafely.com explains how they use CSP on their site.

  • The promises of Content Security Policy to secure the web

The CSP policy is enforced by the browser. Therefore, assuming you have set a proper CSP policy, and assuming your browser doesn't have bugs, there is no way to bypass CSP. That's one of the attractions of CSP.

Note that some browsers (e.g., IE10 and earlier versions of IE, if I recall correctly) don't support CSP.

Be warned that CSP is not a silver bullet:

  • CSP does not stop DOM-based XSS (also known as client-side XSS) if you enable 'unsafe-eval' in your CSP policy. To prevent DOM-based XSS, you must write your Javascript carefully to avoid introducing such vulnerabilities.

  • CSP stops most forms of script injection, but it does not stop markup injection: see, e.g., Postcards from the post-XSS world as well as the HTML form injection attack from Section III-A of Self-Exfiltration: The Dangers of Browser-Enforced Information Flow Control (Chen et al, W2SP 2012). So, you still will want to avoid introducing injection bugs into your code.

See also A few things beyond the scope of Content Security Policy for more discussion of some problems that CSP doesn't solve.


CSP works by enforcing that certain content policies are placed upon scripts, e.g. "no external scripts", or "no inline scripts". This makes XSS a whole lot harder, because 99% of XSS cases involve inline scripts or references to off-site scripts. The only downside is that it pretty much forbids JavaScript entirely, and it can be very difficult to produce a JavaScript-enabled site that adheres to the CSP.

Bypassing may be possible, depending on the policy used and the type of vulnerability you have, but in general it's a pretty solid system. For sites with sensitive content and no JavaScript, I'd highly recommend setting a restrictive policy.