Browser Defense in Depth:
- Definition: Content Security Policy (CSP) is an HTTP response header that restricts the resources (scripts, styles, images, iframes) the browser is allowed to load and execute for a given page.
1. How CSP Blocks XSS:
- Disables Inline Execution: By default, a strict CSP rejects inline tags, inline event attributes (onclick='...'), and javascript:... URLs. If an attacker injects a malicious tag via an unescaped comment, the browser refuses to execute it.
- Restricts Script Origins: Directives like script-src 'self' https://trusted-cdn.com dictate that only scripts fetched from approved domains can execute.
- Disables eval(): Bans dynamic string evaluation (eval(), new Function()) unless explicitly overridden with 'unsafe-eval'.
2. Modern CSP Techniques (Nonce vs Hash):
- Nonce-based: Server generates a unique cryptographic random nonce per request, attaching it to the header (script-src 'nonce-abc123') and to legitimate server-rendered script tags (). Injected scripts lack the secret nonce and fail to execute.
3. Monitoring Mode:
- Use Content-Security-Policy-Report-Only during initial rollout to log policy violations to a reporting endpoint without breaking user experience.