Content Security Policy Header is a security feature implemented in web browsers to prevent a range of attacks, such as Cross-Site Scripting (XSS), clickjacking, and data injection attacks. It is a HTTP header that allows web developers to control which content is allowed to be loaded and executed on a web page.
In simple terms, a CSP header is a set of security rules that allows website owners to control which content can be loaded on their site. By setting up a CSP header, you can prevent malicious content from executing, protecting your site from a range of attacks.
How Does CSP Work?
When you visit a website, your browser loads a bunch of resources, such as images, scripts, and styles. Without proper controls, malicious scripts could sneak in and compromise your site’s security. CSP solves this problem by restricting where resources can be loaded from.
Here’s how it works:
- CSP is included in HTTP headers: The website’s server sends a CSP header in its response to your browser.
- The browser checks the rules: When your browser loads the page, it checks the CSP header to see if it’s allowed to load content from a certain source.
- Enforcement: If the content doesn’t follow the CSP rules, your browser blocks it. This helps prevent harmful content from being executed.
Think of it as a “security guard” that checks every resource before letting it onto your website.
Key Directives of a CSP Header
CSP headers come with different rules (called directives) that specify which types of content are allowed and from which sources. Here’s a quick overview of all the directives:
| Directive | What It Does | Example |
|---|---|---|
| default-src | Sets a default rule for all content types. | default-src 'self'; |
| script-src | Specifies where JavaScript can come from. | script-src 'self' https://trusted.com; |
| style-src | Controls where CSS styles can be loaded from. | style-src 'self' 'unsafe-inline'; |
| img-src | Sets trusted sources for images. | img-src 'self' https://images.com; |
| connect-src | Specifies where XMLHttpRequests (AJAX) and WebSocket connections can go. | connect-src 'self' https://api.com; |
| font-src | Defines where fonts can be loaded from. | font-src 'self' https://fonts.com; |
| object-src | Specifies where <object>, <embed>, and <applet> tags can load content from. | object-src 'none'; |
| frame-ancestors | Controls where the site can be embedded (in a frame). | frame-ancestors 'none'; |
| child-src | Specifies allowed sources for nested frames (iframes). | child-src 'self'; |
| base-uri | Restricts the base URL for the page. | base-uri 'self'; |
| form-action | Specifies where form submissions can be sent. | form-action 'self'; |
| manifest-src | Specifies where the web app manifest file can be loaded from. | manifest-src 'self' https://trusted-manifest.com; |
| media-src | Specifies allowed sources for media (audio and video). | media-src 'self' https://media.com; |
| worker-src | Specifies allowed sources for Worker, SharedWorker, or ServiceWorker scripts. | worker-src 'self' https://workers.com; |
| navigate-to | Controls where the current page can navigate (links or JavaScript navigation). | navigate-to 'self' https://trusted-site.com; |
| frame-src | Specifies where content in <frame>, <iframe>, <object>, <embed>, and <applet> tags can come from. | frame-src 'self' https://trusted-iframe.com; |
| upgrade-insecure-requests | Allows the browser to automatically upgrade insecure HTTP requests to HTTPS. | upgrade-insecure-requests; |
| block-all-mixed-content | Prevents any mixed content (i.e., content served over HTTP on an HTTPS page). | block-all-mixed-content; |
| require-trusted-types-for | Ensures that only scripts that adhere to a specific Trusted Types policy can be executed. | require-trusted-types-for 'script'; |
| Content-Security-Policy-Report-Only | Allows a site to report violations of its CSP without enforcing the policy (useful for testing). | Content-Security-Policy-Report-Only: default-src 'self'; |
Examples of CSP Headers
1. Basic CSP Example: Allow only resources from the same domain
Content-Security-Policy: default-src 'self';
This is the simplest CSP rule. It says that only content from the same origin (i.e., your own website) is allowed to load. Using 'self' as a directive for default-src essentially means “allow everything to load only from this website”. By doing this, it blocks any external resources, making it much harder for attackers to inject harmful content or execute scripts from unauthorized sources.
2. Allowing Trusted Domains: Allow resources from your own site and a few trusted external domains
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.com; style-src 'self';
This rule allows:
- All content from your website (
'self') - JavaScript from both your website and
https://trusted.com - CSS only from your site
By using 'self', it ensures that no scripts or other resources can be loaded from an untrusted domain, which is a common method for attackers to inject malicious content. Only scripts from https://trusted.com are allowed to execute, protecting the website from cross-site script injection (XSS) from external, potentially malicious sources.
3. Allowing Inline Scripts: This isn’t generally recommended for security, but you can enable it
Content-Security-Policy: script-src 'self' 'unsafe-inline';
This rule lets inline JavaScript run but be cautious – this can weaken your CSP and make your site more vulnerable. Allowing inline scripts is risky because attackers can inject malicious inline scripts into the HTML or other parts of your page. Instead of relying on 'unsafe-inline', it’s better to move inline JavaScript into separate files, which can be more easily controlled by your CSP.
Real-Life Scenarios: Why Use CSP?
Scenario 1: Preventing XSS (Cross-Site Scripting)
XSS attacks happen when an attacker injects malicious scripts into your website. For example, a website that allows users to leave comments might get targeted, where an attacker adds a script that steals other users’ cookies.
Solution: By setting a strict CSP, you can block any unauthorized scripts from executing.
Content-Security-Policy: script-src 'self';
In this case, 'self' ensures that only scripts from your website can run, blocking any scripts that are injected into the page, either via a comment section or some other form of input. This effectively prevents XSS attacks, which rely on executing unauthorized scripts.
Scenario 2: Blocking Malicious External Resources
What if an attacker hijacks a third-party server to serve malware to your site? This could happen if your site loads resources like images or scripts from untrusted sources.
Solution: By restricting where images and scripts can come from, you can ensure that they are only loaded from safe, trusted domains.
Content-Security-Policy: img-src 'self' https://trusted-images.com; script-src 'self' https://trusted-scripts.com;
Here, 'self' ensures that images and scripts can only come from your own website, while also allowing specific trusted external sources like https://trusted-images.com. This significantly reduces the risk of an attacker serving harmful images or scripts from external, untrusted locations.
Scenario 3: Preventing Clickjacking
Clickjacking occurs when an attacker places an invisible frame over your website, tricking users into clicking hidden buttons or links. This can lead to users unknowingly performing actions on your site or revealing sensitive information.
Solution: Use the frame-ancestors directive to prevent your site from being embedded in any frame.
Content-Security-Policy: frame-ancestors 'none';
This directive ensures that your site can’t be embedded in any iframe, preventing attackers from performing clickjacking attacks. By using 'none', you make sure that no website can load your page within an iframe, thus protecting your users.
Benefits of Using Content Security Policy
- Enhanced Security: CSP is one of the most effective ways to defend against XSS and other malicious attacks. By controlling which resources are allowed to load, you significantly reduce the risk of harmful content being injected.
- Prevents Unauthorized Content: If someone tries to load content from an unapproved source (like a malicious script), CSP will stop it in its tracks.
- Protection from Data Theft: CSP helps prevent attackers from stealing sensitive user data by blocking malicious scripts from executing on your site.
- Improved User Experience: A well-configured CSP can stop unwanted pop-ups, redirects, and other annoying or harmful behaviors that could affect your users.
Challenges of Setting Up CSP
- Breaking Legacy Code: If you have an older site that relies heavily on inline JavaScript or external scripts, switching to a strict CSP might break some functionality. You may need to update your code to follow the new rules.
- Inline Scripts: Many websites use inline scripts, which CSP generally blocks. To allow these safely, you’ll need to use things like nonces or hashes to specify which inline scripts are trusted.
- CSP Reporting: CSP can sometimes cause issues if it’s misconfigured. To help you troubleshoot, you can use the
report-uridirective to get reports on what was blocked by your CSP.
Conclusion
Though setting up CSP can be tricky, especially if you’re dealing with legacy code or inline scripts, the security benefits are well worth the effort. By implementing CSP, you’re not just protecting your website; you’re also giving your users a safer, more secure browsing experience.
With CSP, you’re putting up a strong defense against many common web vulnerabilities – making your site much harder for attackers to exploit the vulnerabilities. Just make sure to plan your policy carefully, especially if your website relies on external resources or inline scripts.









There is noticeably a bundle to know about this. I assume you made certain nice points in features also.
Glad to be one of several visitants on this awing website : D.