Content-Security-Policy
- What it does
- CSP lists where your page is allowed to load scripts, styles, images, frames and connections from. Anything not on the list gets blocked. It's the best header-level defence against cross-site scripting you have.
- Risk if missing
- With no CSP, any script that gets onto the page (an XSS bug, a compromised analytics tag, a Magecart skimmer) runs with full access to your users' sessions and whatever they type into your forms.
Recommended value: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: https:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'; upgrade-insecure-requests
// aws cloudfront create-response-headers-policy --response-headers-policy-config file://policy.json
{
"Name": "fixsecurityheaders-policy",
"SecurityHeadersConfig": {
"ContentSecurityPolicy": {
"Override": true,
"ContentSecurityPolicy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: https:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'; upgrade-insecure-requests"
}
},
"CustomHeadersConfig": {
"Quantity": 0,
"Items": []
}
}Gotchas
- Ship it as Content-Security-Policy-Report-Only first and read the violation reports for a week or two before you enforce.
- 'unsafe-inline' or 'unsafe-eval' in script-src throws away most of the XSS protection. Use nonces or hashes instead.
- Analytics, chat widgets and payment iframes each need their hosts added. Expect to find a few you forgot about.
- Send one CSP header, not two. Multiple policies are intersected, so the result is usually stricter than either one and things break in confusing ways.