Advanced CSP Configurations
1. Introduction
Content Security Policy (CSP) is a security feature that helps prevent a variety of attacks such as Cross-Site Scripting (XSS) and data injection attacks. By defining a CSP, you can control the sources from which content can be loaded in your web application.
2. CSP Directives
CSP uses a set of directives that specify which resources are allowed to load. Here are some key directives:
- default-src: Serves as a fallback for other directives.
- script-src: Defines valid sources for JavaScript.
- style-src: Defines valid sources for stylesheets.
- img-src: Defines valid sources for images.
- connect-src: Defines valid sources for fetching resources using fetch, XMLHttpRequest, WebSocket, and EventSource.
3. Advanced Configurations
Advanced CSP configurations enable more granular control over content loading. Here are some configurations to consider:
- Nonce-based CSP: Use
nonce-
to allow inline scripts/styles while keeping a strict policy. - Hash-based CSP: Use a hash value of allowed inline scripts/styles to permit them without the risk of XSS.
- Report-Only Mode: Use
Content-Security-Policy-Report-Only
to test your policy without enforcing it.
3.1 Nonce-based CSP
To use a nonce, generate a unique value for each request and include it in the CSP header and the corresponding script/style tags.
Content-Security-Policy: script-src 'self' 'nonce-';
3.2 Hash-based CSP
To allow specific inline scripts, calculate the SHA-256 hash of the script and include it in the CSP header.
Content-Security-Policy: script-src 'self' 'sha256-';
3.3 Report-Only Mode
When testing a CSP policy, use the report-only header to receive violation reports without blocking any content.
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report-endpoint;
4. Code Examples
<script nonce="abc123">
console.log('This is an inline script.');
</script>
5. Best Practices
Implementing CSP effectively requires careful planning. Here are some best practices:
- Start with a report-only policy to identify potential issues.
- Gradually tighten your CSP as you gain confidence.
- Avoid using
unsafe-inline
andunsafe-eval
. - Utilize nonces or hashes for inline scripts/styles.
- Regularly review and update your CSP as your application evolves.
6. FAQ
What is CSP?
CSP is a security feature that helps prevent attacks such as XSS by controlling the resources that can be loaded on a web page.
How do I implement CSP?
Implement CSP by setting the Content-Security-Policy
header in your web server configuration or HTML document.
Can CSP block legitimate content?
Yes, if not configured correctly, CSP can block legitimate resources. It's important to test policies in report-only mode first.
Flowchart of CSP Implementation
graph TD;
A[Start] --> B{CSP Policy};
B -->|Test| C[Report-Only Mode];
C --> D{Issues Detected?};
D -->|Yes| E[Adjust Policy];
D -->|No| F[Implement Policy];
F --> G[Monitor Reports];
G --> H[End];