[dreamhack] Exercise : Cookie

남다은·2023년 2월 16일
0

web hacking

목록 보기
4/12

문제 목표 및 기능

관리자 권한을 획득해 FLAG를 획득하는 것이 목표이다.
문제에서는 두 페이지를 제공한다.

  • /
    -> 이용자의 username을 출력하고 관리자 계정인지 확인함
  • /login
    -> username, password를 입력받고 로그인한다.

웹 서비스 분석

📌 엔드포인트 : /

@app.route('/') # / 페이지 라우팅 
def index():
    username = request.cookies.get('username', None) # 이용자가 전송한 쿠키의 username 입력값을 가져옴
    if username: # username 입력값이 존재하는 경우
        return render_template('index.html', text=f'Hello {username}, {"flag is " + FLAG if username == "admin" else "you are not admin"}') # "admin"인 경우 FLAG 출력, 아닌 경우 "you are not admin" 출력
    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"}') # "admin"인 경우 FLAG 출력, 아닌 경우 "you are not admin" 출력

위의 코드에서 리턴값을 보면, username이 admin인 경우에 FLAG를 출력하도록 되어있는 걸 확인할 수 있다.

📌 엔드포인트 : /login

@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')) )
            resp.set_cookie('username', username)
            return resp 
        return '<script>alert("wrong password");history.go(-1);</script>'

다음의 코드는 로그인 페이지를 구성하는 코드이다.
코드를 살펴보면 method에 따라 다른 기능을 수행하는 걸 확인할 수 있다.

GET

    if request.method == 'GET':
        return render_template('login.html')

usernamepassword를 입력할 수 있는 로그인 페이지를 제공한다.

POST

    elif request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        try:
            # you cannot know admin's pw
            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(32).hex()
            session_storage[session_id] = username
            resp.set_cookie('sessionid', session_id)
            return resp
        return '<script>alert("wrong password");history.go(-1);</script>'

사용자가 입력한 usernamepassword의 입력값을 가져온 다음 users의 변수값과 비교한다.

usernameusers 변수에 존재하면 password도 체크하고 index 페이지로 이동하도록 한다.(username과 password가 다른 경우는 오류라고 출력)

try:
    FLAG = open('./flag.txt', 'r').read() # flag.txt 파일로부터 FLAG 데이터를 가져옴.
except:
    FLAG = '[**FLAG**]'
users = {
    'guest': 'guest',
    'admin': FLAG # FLAG 데이터를 패스워드로 선언
}

users변수가 선언된 부분의 코드를 살펴보면 다음과 같다.
guest의 비밀번호는 guest, admin의 비밀번호는 FLAG임을 확인할 수 있다.


📌 취약점 분석

@app.route('/')
def index():
    session_id = request.cookies.get('sessionid', None)
    try:
        # get username from session_storage
        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"}')

다음 코드를 살펴보면 이용자의 계정을 나타내는 username변수가 요청에 포함된 쿠키에 의해 결정되어 문제가 발생한다.

쿠키는 클라이언트의 요청에 포함되는 정보이기 때문에 이용자가 임의로 조작할 수 있다. 서버는 별다른 검증 없이 이용자 요청에 포함된 쿠키를 신뢰하고, 이용자 인증 정보를 식별한다.
따라서 공격자는 쿠키에 타 계정 정보를 삽입해 계정을 탈취할 수 있다.


📌 익스플로잇

취약점 분석을 통해 알아본 걸 토대로, username을 guest에서 admin으로 조작하면 FLAG를 출력할 수 있다고 예측가능하다.

username을 admin으로 변경한 뒤, 새로고침을 해주니 FLAG를 획득할 수 있었다 :D

profile
차곡차곡 쌓아나가는 WEB FE 개발자

0개의 댓글