Explain the concept of Content Security Policy (CSP) and how it enhances security
TL;DR
Content Security Policy (CSP) is a security feature that helps prevent various types of attacks, such as Cross-Site Scripting (XSS) and data injection attacks, by specifying which content sources are trusted. It works by allowing developers to define a whitelist of trusted sources for content like scripts, styles, and images. This is done through HTTP headers or meta tags. For example, you can use the Content-Security-Policy
header to specify that only scripts from your own domain should be executed:
Content-Security-Policy: script-src 'self'
What is Content Security Policy (CSP)?
Content Security Policy (CSP) is a security standard introduced to mitigate a range of attacks, including Cross-Site Scripting (XSS) and data injection attacks. CSP allows web developers to control the resources that a user agent is allowed to load for a given page. By specifying a whitelist of trusted content sources, CSP helps to prevent the execution of malicious content.
How CSP works
CSP works by allowing developers to define a set of rules that specify which sources of content are considered trustworthy. These rules are delivered to the browser via HTTP headers or meta tags. When the browser loads a page, it checks the CSP rules and blocks any content that does not match the specified sources.
Example of a CSP header
Here is an example of a simple CSP header that only allows scripts from the same origin:
Content-Security-Policy: script-src 'self'
This policy tells the browser to only execute scripts that are loaded from the same origin as the page itself.
Common directives
default-src
: Serves as a fallback for other resource types when they are not explicitly defined.script-src
: Specifies valid sources for JavaScript.style-src
: Specifies valid sources for CSS.img-src
: Specifies valid sources for images.connect-src
: Specifies valid sources for AJAX, WebSocket, and EventSource connections.font-src
: Specifies valid sources for fonts.object-src
: Specifies valid sources for plugins like Flash.
Benefits of using CSP
- Mitigates XSS attacks: By restricting the sources from which scripts can be loaded, CSP helps to prevent the execution of malicious scripts.
- Prevents data injection attacks: CSP can block the loading of malicious resources that could be used to steal data or perform other harmful actions.
- Improves security posture: Implementing CSP is a proactive measure that enhances the overall security of a web application.
Implementing CSP
CSP can be implemented using HTTP headers or meta tags. The HTTP header approach is generally preferred because it is more secure and cannot be easily overridden by attackers.
Using HTTP headers
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com
Using meta tags
<metahttp-equiv="Content-Security-Policy"content="default-src 'self'; script-src 'self' https://trusted.cdn.com" />