Content Security Policy (CSP) Bypass
Overview
Content Security Policy (CSP) is a browser security mechanism used to define where scripts and other resources can be loaded or executed from. This module demonstrates common implementation mistakes that allow attackers to bypass CSP protections. Important: The vulnerabilities demonstrated here are not flaws in CSP itself, but rather mistakes in how developers implement the policy.Objective
Bypass Content Security Policy protections and execute JavaScript in the page across different security levels.Security Levels
Low Level
Vulnerable Code
The low level uses a permissive CSP that allows scripts from multiple external domains:vulnerabilities/csp/source/medium.php:3-18
Exploitation
The implementation makes critical mistakes:- Static Nonce: The nonce value
TmV2ZXIgZ29pbmcgdG8gZ2l2ZSB5b3UgdXA=never changes - unsafe-inline allowed: This directive defeats the purpose of using a nonce
- Direct output: User input is directly included in the page
vulnerabilities/csp/source/high.php:2-21
Exploitation
The page loadssource/high.js which makes a JSONP call to jsonp.php with a callback parameter. Since JSONP responses are executed as JavaScript, you can:
- Modify
source/jsonp.phpto return malicious code instead of the expected callback - The code will execute because it comes from the same origin (
'self')
Key Vulnerability
JSONP is inherently incompatible with strict CSP because it requires dynamic code execution. Any JSONP endpoint becomes a potential CSP bypass.Impossible Level
Secure Code
Best Practices
DO:
- Generate cryptographically random nonces for each request
- Use
'strict-dynamic'for modern browsers - Minimize external script sources
- Use subresource integrity (SRI) for third-party scripts
- Implement CSP in report-only mode first, then enforce
Testing Tools
- Browser DevTools: Check Console for CSP violations
- CSP Evaluator: https://csp-evaluator.withgoogle.com/
- Report-URI: Monitor CSP violations in production
References
- Content Security Policy Reference
- MDN: Content Security Policy
- Mozilla Security Blog: CSP for the Web We Have
Module developed by Digininja
