avatar

Neil Robinson

Content Security Policy

Diagram showing various tags wired an application server

Content Security Policies.

History

When the World Wide Web was created by Tim Berners-Lee back in early 1990s, the idea was to share information, particularly at CERN where Tim worked. The idea was to coalesce all the information throughout CERN in a unified system. Sharing of information was the major problem he was solving. The idea of hyperlinks to various URIs or URLs was the goal to spread and share information at CERN. But as Internet became popular and used outside of CERN, and malicious actors started to appear, and site owners needed a mechanism to restrict hyperlinks or URLs on their websites.

The Cross-Site Scripting (XSS) is a big problem, it was ranked 7th in 2017 and combined with Injection for 3rd place in 2021. 1 It is an important problem to solve. The way we use the web in 2025 is much different 35 years ago. The web use is beyond just sharing of information, we need to protect information as well.

Content Security Policy (CSP) Allow List

Content Security Policy (CSP) is designed to help block malicious scripts that could be injected into web applications. The malicious scripts are mostly JavaScript links to otherwise sites to perform actions that the either the website owner or website user does not authorize to perform. But there are many other attack vectors other than just JavaScript links. Therefore, the Content Security Policy covers many areas such as: html script, img, form, tags, XMLHttpRequest (), etc. 2 It is a large domain.

The CSP is an allow list. The CSP is told what scripts are allowed to run, typically this means only the web application itself and perhaps it Content Delivery Network (CDN), if used.

nonce

In addition, there is another feature of CSP that allows a nonce to be added to each script’s tags attribute, and the nonce must be generated differently (unguessable) as a Base64 encoded string for each http request, this will ensure no script is tampered with, and the malicious actor will not be able to guess this nonce. For a script to run the nonce must agree to the one generated by the server. If not, the script will not run.

Warnings of CSP directives

The unsafe-inline directive should be avoided at all cost since it defeats the purpose of having a CSP. This essentially would not stop any malicious script from being run. 3

Rails Implementation

Rails has a DSL in the application config content_security_policy method that will help you prepare CSP for the Rails application. 4

In addition, adding nonce is straight-forward too with config content_security_policy_nonce_generator method.

Cover image credit 5

Sources:

comments powered by Disqus

tags