Content-Security-Policy (CSP)
The Content-Security-Policy (CSP) is one of the most critical security headers you can implement. It serves as an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks.
How CSP Works
By default, web browsers trust the content they receive from a server. If an attacker manages to inject a malicious script into a page, the browser will execute it because it has no way of knowing the script shouldn't be there.
CSP solves this by allowing site administrators to declare approved sources of content that the browser is allowed to load. By specifying a Content-Security-Policy HTTP response header, you can dictate exactly where scripts, styles, images, and other resources can be loaded from.
Basic Example
Content-Security-Policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com
This policy dictates that:
- By default, resources can only be loaded from the same origin (
'self'). - Images can be loaded from anywhere (
*). - Media can only be loaded from
media1.comandmedia2.com. - Executable scripts can only be loaded from
userscripts.example.com.
Common Pitfalls
The most common mistake when implementing CSP is relying on 'unsafe-inline' for scripts or styles. This completely defeats the purpose of the policy against XSS because it allows any inline script (including those injected by attackers) to execute.
If you need inline scripts, use cryptographic nonces or hashes instead.
Check Your CSP
Not sure if your CSP is tight enough? Use the SecurityHeaders.nl scanner to check your policy against modern best practices.