Content Security Policy (CSP)
Content Security Policy (CSP) is a security standard introduced by the World Wide Web Consortium (W3C) to mitigate and detect certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are often used to inject malicious content into web pages viewed by users. CSP provides a way for web developers to declare approved sources of content that browsers should be allowed to load on a given page.
History
CSP was initially proposed by Mozilla in 2010 to address the growing concern over XSS attacks. Here is a brief timeline:
- 2010: Mozilla introduces CSP as part of Firefox 4.
- 2012: CSP Level 1 is published as a W3C Candidate Recommendation [1].
- 2015: CSP Level 2 becomes a W3C Recommendation [2].
- 2018: CSP Level 3 reaches Candidate Recommendation status, introducing new directives and more granular controls [3].
How CSP Works
CSP can be implemented through:
- HTTP Header: Using the
Content-Security-Policy
HTTP header to specify the policy.
- Meta Element: For documents served with a text/html MIME type, CSP can be set using a
<meta>
element, though this method has limitations compared to the HTTP header.
The policy itself is defined through a set of directives, each controlling different aspects of content loading:
default-src
- Defines the default policy for fetching resources like images, scripts, etc.
script-src
- Restricts the sources of scripts.
style-src
- Controls stylesheets.
img-src
- Specifies valid sources for images.
connect-src
- Limits the URLs which can be loaded using script interfaces like XHR.
Implementation and Benefits
By specifying what content is allowed to be loaded, CSP helps:
- Prevent XSS by blocking inline scripts and eval() calls.
- Prevent clickjacking by controlling where frames can be loaded from.
- Report violations to a specified URL, allowing developers to monitor and react to attempted breaches.
- Reduce the risk of man-in-the-middle attacks by enforcing strict loading policies.
Challenges and Considerations
- Compatibility: Not all browsers support all CSP directives equally, which might require fallback policies.
- Performance: While CSP itself doesn't directly impact performance, poorly configured policies can lead to unnecessary network requests or slow down the parsing of policies.
- Dynamic Content: CSP can complicate dynamic content generation, especially when using inline scripts or styles.
Resources
- [4] - Mozilla Developer Network's CSP guide.
Related Topics