Content Security Policy (CSP)
Content Security Policy (CSP) is a security standard implemented via an HTTP response header that allows website operators to control which resources the browser is allowed to load and execute. It serves as a critical defence against Cross-Site Scripting and other injection attacks.
Content Security Policy provides a declarative mechanism for web developers to specify approved sources of content that browsers should be allowed to load on a given page. By defining a whitelist of trusted content sources, CSP dramatically reduces the attack surface for Cross-Site Scripting (XSS) attacks, even if an injection vulnerability exists in the application code.
A CSP is delivered via the Content-Security-Policy HTTP response header and consists of a set of directives. Key directives include default-src (fallback for other directives), script-src (controls JavaScript sources), style-src (controls CSS sources), img-src (controls image sources), and connect-src (controls fetch, XMLHttpRequest, and WebSocket connections). Each directive specifies one or more allowed sources using keywords like 'self', 'none', or specific domain names.
Modern CSP also supports nonce-based and hash-based approaches, which are more secure than domain-based allowlists. With nonce-based CSP, each inline script is given a unique cryptographic nonce that must match the value specified in the header, making it extremely difficult for injected scripts to execute.
Deploying CSP effectively involves starting in report-only mode to identify violations without breaking functionality, iteratively tightening the policy, eliminating inline scripts and styles where possible, and monitoring CSP violation reports to detect both policy issues and potential attacks.