Skip to main content

Steps for better Content Security Policy rollouts

· 3 min read
Daniel Ruf
Full Stack Developer

Web applications often have bugs, which can lead to security issues. To mitigate the risk of such vulnerabilities, developers can use different solutions. One of them is Content Security Policy (CSP).

With CSP we can prevent Cross-Site Scripting (XSS) and code injections by applying rules which tell the browser, what it is allowed to load. This is a much more flexible and robust solution compared to the old X-XSS header, which was deprecated and removed in favor of CSP.

Use in production environments requires some good planning, testing, and monitoring. The following steps roughly outline a good approach.

1. Technical requirements

  • used server / software
  • identify the place to add headers
  • third-party resources to cover

In the beginning, it makes sense to know the technical details and requirements for the setup. Depending on the used server software, framework, and used resources (like trackers), we have a better picture of the next steps.

2. Rule creation

When creating the CSP rules, we have to consider, that there are different versions of CSP. These are CSP 1.0, CSP Level 2, and CSP Level 3. The newest version brings new directives and supports more features. An overview of the available directives and browser support is available here. Tools like Laboratory by Mozilla and CSP Validators like the one from Google can make it easier, to create the correct rules.

Testing should be done locally and on staging / test systems.

3. Monitoring setup

CSP can be deployed in a monitoring-only mode (Content-Security-Policy-Report-Only). This combined with some server-side logging via report-uri makes it easier to test the rules. It's recommended to start with this step in the production environment, to catch any issues caused by each rule, if they would be active.

4. Production rollout

  • apply rules with changes
  • enable logging if you think there may be issues and catch issues early (recommended)

With the information from the previous step, we can fine-tune the CSP rules and deploy them in normal mode. Further monitoring can be helpful and is recommended but this is not a requirement. Otherwise, with such monitoring in production, you can always catch new issues, if new (external) resources are blocked, which shouldn't be the case. Also the monitoring helps you to get notified of XSS attacks and work on the further hardening of the applications.

There are many more useful resources around CSP. The following links are just a few: