Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[이병영/yi-barrack]: python PIL-CVE-2017-8291 분석 코드 및 결과 #175

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added python/PIL-CVE-2017-8291/01.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added python/PIL-CVE-2017-8291/02.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
67 changes: 67 additions & 0 deletions python/PIL-CVE-2017-8291/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Python PIL RCE(GhostButt )

> [이병영 (@yi-barrack)](https://github.com/yi-barrack)


### 요약

Python에서 이미지 처리를 담당하는 모듈 PIL(Pillow)은 내부적으로 GhostScript를 호출하기 때문에 GhostButt 취약점 (CVE-2017-8291)의 영향을 받아 원격 명령 실행 취약점이 발생한다.

GhostButt 취약점(CVE-2017-8291)
- Ghostscript는 -dSAFER 옵션을 통해 안전 모드를 제공하지만, 이 취약점을 통해 안전 모드를 우회함
- 공격자를 특수하게 조작된 .eps 문서를 만들어 Ghostscript 입력으로 제공하게 됨
- Ghostscript가 이 문서를 처리하는 과정에서 유형 혼동이 발생하여, 공격자가 임의의 명령을 실행할 수 있게 됨
<br>


### 환경 구성 및 실행

- `docker compose up -d` 커맨드를 입력해 테스트 환경을 실행
- `http://your-ip:8000/` 에 접속하여 파일 업로드 웹 페이지 확인
![](02.png)
- 조작된 poc.png 파일 업로드

<br>
<br>

정상적인 기능은 PNG 파일을 업로드하면 백엔드에서 PIL을 호출하여 이미지를 로드하고, 가로 세로 크기를 출력함. 하지만, 백엔드는 파일 헤더를 통해 이미지 유형을 판단하기 때문에 확장자 검사를 무시하고, 실행 가능한 명령이 포함된 EPS 파일을 PNG 확장자로 변경하여 업로드할 수 있음.

예를 들어,[poc.png](poc.png),파일을 업로드하면 `touch /tmp/aaaaa`명령이 실행됨. POC 파일 내의 명령을 리버스 쉘 명령으로 변경하면 쉘을 획득할 수 있음.
해당 poc.png 파일을 업로드 후 docker에 접속하여 /tmp 에 가보면 touch /tmp/aaaaa명령에 의해 aaaaa 파일이 생성된 것을 확인 가능함



```python
command = ["gs",
"-q", # quiet mode
"-g%dx%d" % size, # set output geometry (pixels)
"-r%fx%f" % res, # set input DPI (dots per inch)
"-dBATCH", # exit after processing
"-dNOPAUSE", # don't pause between pages,
"-dSAFER", # safe mode
"-sDEVICE=ppmraw", # ppm driver
"-sOutputFile=%s" % outfile, # output file
"-c", "%d %d translate" % (-bbox[0], -bbox[1]),
# adjust for image origin
"-f", infile, # input file
]

# GhostScript 설치 여부 판단 코드 생략
try:
with open(os.devnull, 'w+b') as devnull:
subprocess.check_call(command, stdin=devnull, stdout=devnull)
im = Image.open(outfile)
```

<br>
<br>

## 결과
![](01.png)

<br><br>

## 정리
이 취약점은 -dSAFER 옵션을 통해 안전 모드를 설정했지만, GhostScript의 샌드박스 우회 취약점 (GhostButt CVE-2017-8291)으로 인해 이 안전 모드가 우회되어 임의의 명령을 실행할 수 있다. 또한, 현재까지 GhostScript 공식 최신 버전인 9.21도 이 취약점의 영향을 받기 때문에 운영체제에 GhostScript가 설치되어 있다면 PIL에 명령 실행 취약점이 존재한다고 볼 수 있다.


87 changes: 87 additions & 0 deletions python/PIL-CVE-2017-8291/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
''' 이미지 크기 가져오기 앱 '''

# coding=utf-8
import os
from flask import Flask, request, redirect, flash, render_template_string, get_flashed_messages
from PIL import Image
from werkzeug.utils import secure_filename

# 업로드 폴더 설정
UPLOAD_FOLDER = '/tmp'

# 허용되는 파일 확장자
ALLOWED_EXTENSIONS = set(['png'])

# Flask 앱 생성
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'test'

def get_img_size(filepath=""):
''' 이미지 가로/세로 크기 가져오기 '''
try:
img = Image.open(filepath)
img.load()
return img.size
except:
return (0, 0)

def allowed_file(filename):
''' 파일 확장자 유효성 검사 '''
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
''' 파일 업로드 앱 '''
if request.method == 'POST':
# 파일이 요청에 포함되어 있는지 확인
if 'file' not in request.files:
flash('파일이 없습니다.')
return redirect(request.url)

# 업로드된 파일 객체 가져오기
image_file = request.files['file']

# 파일 이름이 비어있는지 확인
if image_file.filename == '':
flash('파일이 선택되지 않았습니다.')
return redirect(request.url)

# 파일 확장자 유효성 검사
if not allowed_file(image_file.filename):
flash('허용되지 않는 파일 형식입니다.')
return redirect(request.url)

# 파일 저장 및 크기 가져오기
if image_file:
filename = secure_filename(image_file.filename)
img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
image_file.save(img_path)
height, width = get_img_size(img_path)

# 이미지 크기 출력
return '<html><body>이미지의 높이 : {}, 너비 : {}; </body></html>'.format(height, width)

# 업로드 폼 렌더링
return render_template_string('''
<!doctype html>
<title>파일 업로드</title>
<h1>파일 업로드</h1>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
''')

if __name__ == '__main__':
app.run(threaded=True, port=8000, host="0.0.0.0")
12 changes: 12 additions & 0 deletions python/PIL-CVE-2017-8291/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Docker Compose 버전 정의
version: '2'

# Docker Container 정의
services:
web:
image: vulhub/ghostscript:9.21-with-flask # vulhub/ghostscript 이미지 사용
command: python app.py # app.py 명령 실행을 통해 Flask 서버 실행
volumes:
- ./app.py:/usr/src/app.py # app.py 파일을 container 내부로 복사
ports:
- "8000:8000" # host와 container의 port mapping
100 changes: 100 additions & 0 deletions python/PIL-CVE-2017-8291/poc.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.