Content Security Policy (CSP)

Content Security Policy(CSP) is a additional security layer implemented in browser which tells browser from which origin resources(scripts, css, frames) are allowed/blocked from loading into a website.

CSP is a response header in format - Content-Security-Policy: <directive> <value> <value>; <directive> <value> <value>;

This prevents variety of vulnerabilities like XSS, Clickjacking, Mixed Content Type etc

Example Usages

  1. Content-Security-Policy: default-src 'self' - To allow resources from only site's origin- to be loaded.

  2. Content-Security-Policy: default-src 'self' example.com *.example.com - To allow loading resources same origin, from trusted domains & subdomains.

  3. Content-Security-Policy: default-src 'self'; img-src *; media-src example.org example.net; script-src userscripts.example.com - To allow images to be loaded from any origin, Media(audio,video src) is allowed to be loaded from specific origin, script is allowed to be loaded from specific origin, anhy other content is allowed to be loaded only from same origin.

  4. Content-Security-Policy: default-src https://onlinebanking.example.com - To allow resources to be loaded only in HTTPS connection from specific website(can be same origin website also, prevents Mixed Content loading).

  5. Content-Security-Policy: frame-ancestors 'self' https://example.com https://*.example.com; - To allow the website to be embedded, provided parent window is having same origin, or example.com or subdomains of example.com with HTTPS scheme.

  6. Content-Security-Policy: frame-ancestors 'none'; - This is equivalent to X-Frame-Options: deny & completely prevents clickjacking as it doesn't allow parent window of any origin to embed the website.

  7. Content-Security-Policy: script-src https://example.com/ - To allow script to be loaded only from example.com, All inline scripts & event handlers such as <script>alert()</script> and <button onclick=myFunc()>Submit</button> will also be blocked.

  8. Content-Security-Policy: script-src 'sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8=' - To allow inline script with specific hash value of it's content to be used.

  9. Content-Security-Policy: script-src 'unsafe-inline' 'unsafe-eval' - To allow usage of inline scrips, event handlers & also allow dynamic javascript execution using eval().

Detailed description & usage of all directives is present available here.

Refer OWASP Cheatsheet to know about defending specific attacks & CSP configurations.

Last updated