보안공부/워게임

wargame [1] file-download-1

mint* 2021. 5. 20. 17:56
728x90

#!/usr/bin/env python3
import os
import shutil

from flask import Flask, request, render_template, redirect

from flag import FLAG

APP = Flask(__name__)

UPLOAD_DIR = 'uploads'


@APP.route('/')
def index():
    files = os.listdir(UPLOAD_DIR)
    return render_template('index.html', files=files)
// index.html 불러오기

@APP.route('/upload', methods=['GET', 'POST']) //get도 이용한다.(url노출)
def upload_memo():
    if request.method == 'POST':
        filename = request.form.get('filename')
        content = request.form.get('content').encode('utf-8')

        if filename.find('..') != -1:
            return render_template('upload_result.html', data='bad characters,,')

//여기서 파일이름이 ..이면 data가 bad characters로 바뀐다. ..을 쓰지않고 /read를 할 수 있을까?

        with open(f'{UPLOAD_DIR}/{filename}', 'wb') as f:
            f.write(content) //파일 이름과 내용으로 게시글 작성하기, uploads/[filename]경로

        return redirect('/')

    return render_template('upload.html')


@APP.route('/read')
def read_memo():
    error = False
    data = b''

    filename = request.args.get('name', '')

    try:
        with open(f'{UPLOAD_DIR}/{filename}', 'rb') as f: 
            data = f.read() //data는 파일 값.
    except (IsADirectoryError, FileNotFoundError):
        error = True


    return render_template('read.html',
                           filename=filename,
                           content=data.decode('utf-8'),
                           error=error)


if __name__ == '__main__':
    if os.path.exists(UPLOAD_DIR):
        shutil.rmtree(UPLOAD_DIR)

    os.mkdir(UPLOAD_DIR)

    APP.run(host='0.0.0.0', port=8000)

 

문제는 flag.py를 다운받는 것이다.

다운 받는다는 것은 파일은 사이트에 있고 그걸 읽으면 된다는 뜻이다. 

/read에는 없을 것이고 상위 디렉토리에 있을 것이다. 

 

get방식은 url에 파라미터를 붙여 전송한다.

뒤에?를 붙여 시작하고 파라미터=값 형식이다. 구분기호는 &이다.

http://host1.dreamhack.games:17811/read?name=d 

..을 금지시키지 않았다면 ../read?name=flag.py를 작성하면

upload/../read?name=flag.py가 되어 다운이 가능했을 것이다.

 

계속해보다가 하나하나 포스팅하는거 귀찮아서 링크를 수정하여 입력했다.

 

 

http://host1.dreamhack.games:17811/read?name=../flag.py

???오잉

 

답이 나온 이유는 파일 이름에 ..을 사용할 수 없지만

@APP.route('/upload', methods=['GET', 'POST'])
def upload_memo():
    if request.method == 'POST':
        filename = request.form.get('filename')
        content = request.form.get('content').encode('utf-8')   

 

   try:
        with open(f'{UPLOAD_DIR}/{filename}', 'rb') as f:
            data = f.read() //파일이 실행된다.
    except (IsADirectoryError, FileNotFoundError):
        error = True

read에서는 파일 이름이 ..을 쓰는지 안쓰는지 검토를 하지 않는다.(업로드 과정에서 처리되었을 거라고 생각했을 것이다.)

그래서 get파라미터를 사용한다는 것을 이용하여 url에 read?name=../flag.py 로 파일이름을 입력해주면

upload가 아닌 read만 실행되므로 flag를 얻을 수 있다.

 

uploads와 upload는 다르다

uploads는 파일을 업로드하고 읽는 공간

/upload는 경로

 

 

728x90