Definition
Content Security Policy (CSP) is an HTTP header used to prevent cross-site scripting (XSS), data injection, and other code execution attacks by specifying which content sources are trusted by the web application.How It Works
- 1A server sends a CSP header with directives that define content sources for various types of resources (scripts, styles, etc.).
- 2The browser reads these directives and enforces them, blocking any resources that do not conform to the policy.
- 3The CSP can include 'script-src', 'style-src', 'default-src', and 'connect-src' directives to specify allowed sources for scripts, styles, default resources, and connections respectively.
- 4Nonce-based and hash-based approaches can be used to allow specific inline scripts and styles by assigning a unique nonce or hash value.
- 5The 'report-uri' directive can be included to send violation reports to a specified endpoint for monitoring purposes.
Key Characteristics
- Directives: Instructions on where content can be loaded from.
- Nonce/Hash: Allows specific inline scripts/styles by using unique identifiers.
- Reporting: Provides a mechanism to report CSP violations.
Comparison
| Concept | Purpose | Primary Use Case |
|---|---|---|
| Content Security Policy | Prevents loading of unwanted resources | XSS and data injection prevention |
| Same-Origin Policy | Restricts requests between different sites | Protects confidentiality and integrity of data |
| Cross-Origin Resource Sharing (CORS) | Allows controlled sharing of resources between sites | Securely sharing resources across domains |
Real-World Example
CVE-2019-16759 exploited a lack of proper CSP, leading to a vulnerability in vBulletin that allowed remote code execution through XSS.Detection & Prevention
- Testing Tools: Use browser DevTools to inspect CSP headers and test violations.
- Implementation: Regularly update CSP policies to reflect new trusted sources.
- Monitoring: Use 'report-uri' to receive reports on policy violations.
Common Misconceptions
- CSP is a silver bullet: While CSP is powerful, it must be part of a broader security strategy.
- 'unsafe-inline' is acceptable: Using 'unsafe-inline' negates many benefits of CSP as it allows execution of inline scripts.
- CSP breaks websites: Properly configured CSP will not break functionality but enhance security.