Changing the Content-Security-Policy (CSP)
Last Modified:
Learning the CSP directives to prevent attacks on your applications.
You can limit URL resources like JavaScript, CSS, images, media, and more by using the Content-Security-Policy HTTP response header. Your website may load certain URLs from specific origins. Creating a CSP can reduce the attack surface of Cross Site Scripting (XSS) attacks or Click Jacking.
According to W3C recommendations, the CSP is now at Level 2, while Level 3 is still in draft form. Before writing a CSP for your application, you must have a thorough understanding of it. Basically, where images, media, and fonts originated, or if you have JavaScript and CSS in line. If you want to protect your application, you must include in the CSP the origin of any script, image, or media domains in your policy.
The CSP does not allow multiple spaces, and each directive is separated by ; Then, you can improve the readability using join(" ", [...]). The CSP can only be tested in a testing environment like QA or Stage. You cannot test it locally (http://localhost:3000), because CSP is in CloudFront, not Next.js. A report from the directives is also necessary to verify whether all of the directives are appropriately implemented or if you overlooked any.
The CSP is configured in the Terraform server's cloudfront.tf file in the application I worked on. I included a few missing directives, like
- default-src`: Fetch fallback for some of the directives
object-src:For Â<object>,Â<embed>Â orÂ<applet>base-uri: allow URLs to be used in HTML src attributesframe-ancestors: ForÂ<frame>Â<iframe>Â<object>Â<embed>Â<applet>style-src: For CSS loadingfont-src: For web fontsimg-src: For images (allows data: URIs and HTTPS)connect-src: For AJAX/fetch requests. Required for thedefault-src 'none'worker-src: For URLs loading as Worker, SharedWorker or ServiceWorker.media-src: For audio and video, e.g., HTML5<video>Â elements.frame-src: For loading frames
I applied SHA-256 hashes of static inline in script-src and style-src instead of nonce-base, because it would change the current logic to create the nonce dynamically.
I made some changes from the old configuration:
- ✅ Removing
unsafe-inlineand addingscript-srcbecause it allows any inline JavaScript, completely bypassing CSP protection. - ✅ Removing
unsafe-inlineand addingstyle-srcbecause it allows any inline CSS, which can be used for data exfiltration.
Regarding CSP Reporting:
- ✅ AddedÂ
report-uri: For older browsers - ✅ AddedÂ
report-to csp-endpoint: For modern browsers - ✅ Added Report-To header: Defines the reporting endpoint properly
The CSP is now complete!
Here is the final CSP implementation:
- ✅ Blocks XSS attacks
- ✅ Prevents clickjacking
- ✅ Controls resource loading
- ✅ Has proper reporting
- ✅ Documents accepted risks
Source: Content-Security-Policy - CSP https://content-security-policy.com/ (opens in a new tab)
