Introduction to Content Security Policy
What is Content Security Policy (CSP)?
Content Security Policy (CSP) is a security feature that helps prevent a variety of attacks, including Cross-Site Scripting (XSS) and data injection attacks. It allows web developers to declare valid sources for content that browsers should be allowed to load on that webpage.
Why Use CSP?
- Minimize the risk of XSS attacks.
- Control resources the user agent is allowed to load for a given page.
- Mitigate data injection attacks.
CSP Directives
CSP uses a set of directives to specify allowed content sources. Here are some key directives:
- default-src: Serves as a fallback for other directives.
- script-src: Restricts JavaScript sources.
- style-src: Restricts CSS sources.
- img-src: Restricts image sources.
- connect-src: Restricts URLs for fetching resources via XMLHttpRequest or WebSocket.
Implementing CSP
CSP can be implemented using HTTP headers. The header looks like this:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.com; style-src 'self' 'unsafe-inline';
This example allows scripts from the same origin and from https://trusted.com
, while styles are allowed from the same origin and inline styles are permitted.
Best Practices
- Start with a report-only mode to monitor violations without enforcing the policy.
- Use strict sources to minimize the risk of attacks.
- Regularly review and update your CSP.
- Test your CSP with browsers’ developer tools to catch issues.
FAQ
What happens if a resource violates the CSP?
The browser will block the resource from loading, and a violation will be logged in the console.
Can I use inline scripts with CSP?
Inline scripts are generally blocked unless you use 'unsafe-inline'
or hashes/nonces to allow them.
How can I test my CSP?
Use browser developer tools to check the console for CSP violations and adjust your policy accordingly.