Understanding Content Security Policy
Understanding Content Security Policy
Content Security Policy provides a powerful second layer of defense against XSS by allowing developers to declare which sources of content browsers should trust. Even if an attacker successfully injects a script tag, CSP can prevent its execution by restricting scripts to trusted sources only. This defense-in-depth approach has proven highly effective, with Google reporting a significant reduction in XSS vulnerabilities after implementing strict CSP across their applications.
CSP works through HTTP headers or meta tags that instruct browsers on content restrictions. The most basic CSP might look like: Content-Security-Policy: default-src 'self'
, which restricts all content to the same origin as the document. Real-world policies are typically more complex, allowing specific sources for different content types. For example, you might allow images from a CDN, styles from your origin plus specific trusted sources, and scripts only from your origin with no inline scripts allowed.
The power of CSP lies in its granular control over different types of content and execution contexts. Beyond basic source restrictions, CSP can require Subresource Integrity for scripts, restrict form submissions to specific endpoints, control plugin types, and even report violations without blocking them. This reporting capability is particularly valuable during CSP implementation, allowing you to identify potential issues before enforcing restrictions that might break functionality.