CSP
Category: Security
What is CSP?
Content Security Policy (CSP) is a security mechanism that helps prevent XSS (Cross-Site Scripting), clickjacking and other attacks through code injection.
How does CSP work?
CSP allows administrators to define from which sources the browser can load resources such as:
- JavaScript
- CSS styles
- Images
- Fonts
- Iframes
- Media files
Basic directives
| Directive | Description |
|---|---|
| default-src | Sets the default source for all resources |
| script-src | Defines allowed sources for JavaScript |
| style-src | Defines allowed sources for CSS styles |
| img-src | Defines allowed sources for images |
| connect-src | Restricts sources for XMLHttpRequest, WebSocket |
| font-src | Defines allowed sources for fonts |
| frame-src | Defines allowed sources for iframes |
Examples of CSP policies
Example 1: Allowing only own resources
Content-Security-Policy: default-src 'self'
Example 2: Allowing specific external domains
Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.google.com; img-src 'self' https://cdn.example.com;
Example 3: Disabling inline JavaScript
Content-Security-Policy: script-src 'self'; object-src 'none'
Special values
- 'none' - Disallows all sources
- 'self' - Allows only from the same domain
- 'unsafe-inline' - Allows inline code (inline)
- 'unsafe-eval' - Allows eval() function
- nonce-<value> - Allows specific inline script
Modes of operation
- Enforce mode - Blocks resources violating the rules
- Report-only mode - Reports only, but does not block (Content-Security-Policy-Report-Only)
Advantages
- Effective protection against XSS attacks
- Control over loaded resources
- Possibility of monitoring and reporting
- Support from all modern browsers