Synonyms: Website Security Policy
CSP stands for Content Security Policy, a security feature used in web development to help protect websites from various attacks, such as Cross-Site Scripting (XSS), data injection, and other forms of malicious code execution. Essentially, CSP acts as a set of rules that define what content can be loaded and executed on a webpage. These rules are implemented via HTTP headers or meta tags.
Why is CSP important?
One of the most common web vulnerabilities is XSS, where attackers inject harmful scripts into a trusted website. These scripts can be used to steal data, hijack user sessions, or perform other malicious activities. A Content Security Policy helps mitigate these risks by controlling which resources (like scripts, images, and styles) are allowed to load and run on a site.
For instance, if you define in your CSP that only scripts from a specific, trusted domain can run, any malicious script from an unauthorized source will be blocked.
Key benefits of CSP:
- Prevents Cross-Site Scripting (XSS): CSP restricts what JavaScript can run, reducing the risk of XSS attacks.
- Control over External Resources: By specifying which domains can serve content (like images, fonts, and scripts), CSP prevents the injection of untrusted resources.
- Reporting Mechanism: CSP can be configured to send reports to the website administrator when a violation occurs, helping developers identify security issues.
How does CSP work?
CSP is set by configuring the Content-Security-Policy HTTP header, which the browser reads when loading a webpage. The policy specifies what types of content are allowed and from which sources. For example:
- Scripts: You can limit JavaScript execution to trusted sources, preventing unauthorized scripts from running.
- Images: You can restrict images to load only from specific domains.
- Frames: CSP can control which domains are allowed to frame your site, reducing the risk of clickjacking.
Here’s a simple example of a CSP header:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-source.com; img-src 'self' https://images.com;
In this example, only resources from the website itself ('self'
) and trusted domains like trusted-source.com
(for scripts) or images.com
(for images) are allowed.
Adoption of CSP
CSP is widely adopted in modern web development, particularly for sites handling sensitive data. By implementing a strong CSP, websites can significantly reduce the attack surface for malicious actors, making the web safer for users. Many major browsers, including Chrome, Firefox, and Safari, support CSP, encouraging its use across the web.