What I learnt from using Content Security Policy.

December 11, 2019

As front end developer at Dreamsolution, I also need to check on Content Security Policy (CSP) errors in our projects. During development you can track down most of the CSP errors if they occur.

What I have experienced is that the error descriptions in Chrome, Firefox and Safari are very cryptic. The origin is sometimes hard to find. For example if you use add blockers in your browser it can trigger CSP errors. If the CSP blocks a base64 url and you know you don't use this in your project, try to disable the add blocker and refresh again. If the CSP error goes away then you know you don't need to take action.

When you set up your CSP you want to make it as strict as possible. But sometimes you have to loosen it a little when using third party libraries (e.g. HighCharts, jQuery etc.). They can throw inline-style or inline-script CSP errors.

There are several ways to loosen your CSP. You can use Nonces or Hashes, if this doesn't work for your project you can choose to allow unsafe-inline content.

If your team works with Django Framework, it is possible to create a View decorator to change the default Content-Security-Policy. With this decorator you can override or add an extra directive ("style-src" is a "directive") to your Django View. This way you don't have to loosen your entire web applications' CSP.

Store third party libraries on your local domain

If you use CDNs to third party libraries you can whitelist these domains. Although it is whitelisted it is not necessarily secure. You don't have control over these domains and attackers might succeed in getting unauthorized access to these domains. If so, they can attack your site.

To avoid this, serve third party libraries from your local domain. And keep these packages up to date by checking their change logs for bug fixes etc.

Firefox CSP error when using SMIL in SVG.

You can get inline-css CSP error in Firefox when animating the following SVG attributes using SMIL:

For some vague reason Firefox's CSP engine thinks that these svg attributes used in the animation are inline styles. If you animate the width or height of an svg element then Firefox has no issues. I reported this bug at Bugzilla. Depending on your project you can use the iframe workaround: load the svg in an iframe with a less strict CSP.

Define CSP for static HTML site

If you have a static html site (like me) you can define your CSP in your .htaccess file. Here's an example:


# CSP
Header set Content-Security-Policy "
    default-src 'none';
    script-src 'self' https://www.google-analytics.com;
    style-src 'self';
    img-src 'self' https://www.google-analytics.com https://*.googleapis.com;
    frame-src 'self';
    connect-src 'self';
    font-src 'self';
    manifest-src 'self';
    base-uri 'none';
"

More information on CSP, check out these links: