This guide shows how Content Security Policy (CSP) HTTP response headers improve the security of a web page by restricting the rendering/execution of styles, scripts, images, form submissions, and AJAX requests to only white-listed hostnames. We will be using a Caddy web server to serve up a CSP-protected web page and Sentry to log violations.
Sentry is a popular service that logs application exceptions, but it can do much more -- it can also log CSP violations.
- Sign up for Sentry here.
- Go to Organization Settings at and tick the
Early Adopter
box. - Create a project and go to Settings → Client Keys (DSN). From there, copy the
CSP Endpoint
field value somewhere, as we'll use it later.
- Clone this repository and
cd
into it. - Make sure Caddy is installed (we're using
v0.9.5
for this demo); if not, download the latest version here or, if you are on a Mac and have Homebrew installed, runbrew install caddy
. - On your terminal, run
CSP_REPORT_URI="[csp-endpoint-you-copied-earlier]" caddy
to serve the web page athttp://localhost:2015
. This command will use theCaddyfile
in the root directory, where restrictions are defined under theContent-Security-Policy
header. - Using your browser's developer tools, open the Console tab to see the violations.
If the report URI key you entered is valid, you should start violation entries on your project dashboard:
This comes in handy when you're trying to debug issues on staging/production environments.
- This guide was done on a Caddy server running on a macOS Sierra machine.
- CSP is supported by most modern browsers; a list of them can be seen here.
- Incorrect syntax will render CSP useless. Try using a free validator like this one if you are setting a number of rules.
- To whitelist base64-encoded images, use
data:
as a trusted domain:
Content-Security-Policy "img-src data:"
- References
- Logging violations with Sentry.io