CTF/웹해킹

[Dreamhack] xss-2 문제 풀이

dDong2 2022. 7. 11. 21:08

보안 공부 중 드림핵이라는 사이트를 만나게 되었고,

드림핵 로드맵에 웹 해킹에 관한 로드맵을 따라가던 중 만난 문제이다.

함께 실습하기는 xss에 관한 코드가 차단되어있지 않았는데,

혼자 실습하기인 xss-2 문제는 xss를 기본적으로 차단하여 우회가 필요하다.

 

xss-2

해당 접속 정보인 가상 환경으로 친절히 안내하여주시니 해당 링크를 열고,

문제 파일을 다운로드 받아준다.

 

해당 링크로 들어가면 다음 페이지들이 나온다.

여기서 간단하게 다운로드 한 파일(app.py)을 분석해보자.

 

def read_url(url, cookie={"name": "name", "value": "value"}):
    cookie.update({"domain": "127.0.0.1"})
    try:
        options = webdriver.ChromeOptions()
        for _ in [
            "headless",
            "window-size=1920x1080",
            "disable-gpu",
            "no-sandbox",
            "disable-dev-shm-usage",
        ]:
            options.add_argument(_)
        driver = webdriver.Chrome("/chromedriver", options=options)
        driver.implicitly_wait(3)
        driver.set_page_load_timeout(3)
        driver.get("http://127.0.0.1:8000/")
        driver.add_cookie(cookie)
        driver.get(url)
    except Exception as e:
        driver.quit()
        # return str(e)
        return False
    driver.quit()
    return True


def check_xss(param, cookie={"name": "name", "value": "value"}):
    url = f"http://127.0.0.1:8000/vuln?param={urllib.parse.quote(param)}"
    return read_url(url, cookie)

해당 파일의 상단부에 선언되어있는 함수이다.

read_url은 cookie에 관한 코드, add_cookie를 통해 쿠키를 추가하는 모습을 확인할 수 있다.

check_xss는 인자를 파라미터와 쿠키를 받고 read_url 함수를 호출하여 url과 쿠키를 반환해준다.

 

@app.route("/")
def index():
    return render_template("index.html")


@app.route("/vuln")
def vuln():
    return render_template("vuln.html")


@app.route("/flag", methods=["GET", "POST"])
def flag():
    if request.method == "GET":
        return render_template("flag.html")
    elif request.method == "POST":
        param = request.form.get("param")
        if not check_xss(param, {"name": "flag", "value": FLAG.strip()}):
            return '<script>alert("wrong??");history.go(-1);</script>'

        return '<script>alert("good");history.go(-1);</script>'


memo_text = ""


@app.route("/memo")
def memo():
    global memo_text
    text = request.args.get("memo", "")
    memo_text += text + "\n"
    return render_template("memo.html", memo=memo_text)

해당 파일의 중후반부이다.

앞서 들어간 홈페이지 nav 항목에 맞게 /, /vuln, /flag, /memo 경로를 설정해준다.

xss-1 문제를 풀어봤으면 알 테지만,

xss-2 문제는 앞선 문제와 달리 /vuln 경로에서 파라미터에 들어가는 값과 상관없이 바로 html을 리턴해준다.

그래서 vuln(xss) page에 들어가면 다음과 같이 나오게 된다.

 

vuln(xss) 페이지 진입한 모습

url에 자동으로 파라미터가 기입되어 있는데 아무것도 뜨지 않는다.....

그 말은 즉슨, script 태그를 차단하고 있다고 할 수 있다.

그래서 간단히 script를 우회할 수 있도록 다음 코드를 넣어봤다

param=<scr<script>ipt>alert(1)</scr</script>

그 결과..

결과는 다음과 같았다.

출력되는 텍스트를 제외하고 <scr, </scr, <script>, </script> 자체를 무언가 필터링한다는 느낌이었다.

그래서 이것저것 검색해보았고, xss 우회를 하기 위해서는 다른 태그 삽입도 가능하다는 것을 공부하였다.

 

이전 xss-1 문제(드림핵 사이트에 풀이가 있어서 올리지 않음.)에서 나왔듯이,

또한, 코드에서 /flag 경로에서 Submit을 POST 하는 버튼을 눌러서 제출하게 되면

wrong?? 또는 good이라는 alert를 띄우게 되어있는데

 

param = request.form.get("param")
        if not check_xss(param, {"name": "flag", "value": FLAG.strip()}):
            return '<script>alert("wrong??");history.go(-1);</script>'

        return '<script>alert("good");history.go(-1);</script>'

해당 코드에서 check_xss에 들어가는 인자인 cookie가 flag와 연관이 있다는 것을 알 수 있다.

그래서 내가 삽입한 코드는 다음과 같다.

 

<img src=x onerror=location.href="/memo?memo="+document.cookie>

위 코드를 /flag 페이지에 들어가서 제출하게 되면 memo 파라미터에 document.cookie가 할당되고

app.py에 나와있듯이 cookie 값을 작성시켜줌과 동시에 flag 값을 획득할 수 있게 된다.

 

/flag 페이지

input 태그의 박스 width가 너무 작아서 임의로 늘려보았다.

이렇게 작성하여 제출하게 되면, 잠시 후 alert로 good이 뜬다.

이후, memo 페이지로 이동하면 된다.

 

flag를 숨겨라!!

끝...

 

위 문제를 풀기 위해서는 앞선 드림핵 사이트에서 xss를 공부하고,

xss가 필터링되어있다는 것을 깨닫고,

xss 우회에 대해 공부하고,

app.py를 분석하고

 

공부하고, 깨닫고, 분석한 내용을 한번 더 복습하여 내 것으로 만들면 좋은 것 같다.

오랜만에 글 올리는데, 꾸준히 해보자.. please…

 

 

모든 문제에 관한 저작권은 드림핵 사이트(dreamhack.io)에 있습니다.