반응형
HackHiJack
HHJ
HackHiJack
전체 방문자
오늘
어제
  • 분류 전체보기 (99)
    • chatGPT (2)
    • pwn (2)
    • 워게임 (32)
    • Reversing (0)
    • Cryptography (12)
    • Web (6)
    • CTFs (16)
    • TryHackMe (6)
    • Go (5)
    • Forensics (18)

블로그 메뉴

  • 홈

공지사항

  • Welcome To HHJ's Blog

인기 글

태그

  • 포렌식
  • 해킹 #TryHackMe #WriteUp #ignite
  • function
  • startup
  • main.go
  • hacking
  • Import
  • forensic
  • main
  • ㅣ
  • rootme
  • analyis
  • package
  • shellctf
  • webhacking.kr
  • go
  • pwnable.kr
  • 암호 #AES #드림핵
  • linkfile
  • func

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
HackHiJack

HHJ

[Dreamhack](writeup) - simple_sqli
워게임

[Dreamhack](writeup) - simple_sqli

2022. 3. 1. 12:09
728x90
반응형

오늘은 드림핵의 simple_sqli를 풀어볼 것이다. 이 문제는 드림핵 강의를 보고 충분히 풀 수 있는 매우 쉬운 문제이다.

 

강의에는 없는 python flask 소스코드를 해석해야 하는 것이 어려운 부분일 수 있겠지만, 그중 절반 정도가 쓸데없는 코드이기 때문에 중요한 부분만 잘 캐치해서 확인하면 된다.

 

먼저 소스코드를 확인해보자.

#!/usr/bin/python3
from flask import Flask, request, render_template, g
import sqlite3
import os
import binascii

app = Flask(__name__)
app.secret_key = os.urandom(32)

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

DATABASE = "database.db"
if os.path.exists(DATABASE) == False:
    db = sqlite3.connect(DATABASE)
    db.execute('create table users(userid char(100), userpassword char(100));')
    db.execute(f'insert into users(userid, userpassword) values ("guest", "guest"), ("admin", "{binascii.hexlify(os.urandom(16)).decode("utf8")}");')
    db.commit()
    db.close()

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    db.row_factory = sqlite3.Row
    return db

def query_db(query, one=True):
    cur = get_db().execute(query)
    rv = cur.fetchall()
    cur.close()
    return (rv[0] if rv else None) if one else rv

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

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

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        userid = request.form.get('userid')
        userpassword = request.form.get('userpassword')
        res = query_db(f'select * from users where userid="{userid}" and userpassword="{userpassword}"')
        if res:
            userid = res[0]
            if userid == 'admin':
                return f'hello {userid} flag is {FLAG}'
            return f'<script>alert("hello {userid}");history.go(-1);</script>'
        return '<script>alert("wrong");history.go(-1);</script>'

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

여기서 우리는 아래와 같은 부분만 확인하면 된다. (이 윗부분은 거의 데이터베이스 설정 부분이라서 굳이 확인하지 않아도 된다)

 

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        userid = request.form.get('userid')
        userpassword = request.form.get('userpassword')
        res = query_db(f'select * from users where userid="{userid}" and userpassword="{userpassword}"')
        if res:
            userid = res[0]
            if userid == 'admin':
                return f'hello {userid} flag is {FLAG}'
            return f'<script>alert("hello {userid}");history.go(-1);</script>'
        return '<script>alert("wrong");history.go(-1);</script>'

먼저 우리가 이 코드에서 얻을 수 있는 점은 다음과 같다.

 

-  sql 구문(로그인할때 사용) : 'select * from users where userid="{userid}" and userpassword="{userpassword}"' 

-  userid와 userpassword를 받는다.

-  admin이라는 userid로 로그인하면 플래그를 얻을 수 있다.

-  이 데이터베이스에는 guest, admin 사용자가 있다.(위쪽 데이터베이스 설정 코드에 사용자를 insert한다.)

-  userid, userpaddwordrk 틀리면 wrong이라는 문자열을 alert한다.

 

우리는 admin의 비밀번호를 모르니 sql injection을 이용해 쿼리 인증 우회를 해야 한다.

 

일단은 쿼리문에서 아무런 필터링이 없어서 sql injection을 할 수 있다.

 

이전 게시물에서 말했듯이 userid에만 admin을 쓰고 뒤에 부분은 주석 처리하면 로그인이 가능할 것이다.

대충 아래처럼 구문을 만들면 된다.

select * from users where userid="admin"--" and userpassword="{userpassword}"

그러면 최종적으로 아이디가 admin인 계정으로 로그인된다는 것으로 만들 수 있다.(=비밀번호는 필요가 없다)

이쯤에서 광고한번 클릭해주세용~~^^

↓

↓

반응형

이제 웹페이지로 가보자.

로그인 칸으로 들어가서 위의 sql구문처럼 될 수 있게 아래와 같은 구문을 넣어준다.(비밀번호는 아무거나 넣으면 된다)

그러면 아래처럼 플래그가 잘 나오는 것을 확인할 수 있다.

728x90
반응형

'워게임' 카테고리의 다른 글

[Webhacking.kr] - old 58 (writeup)  (0) 2022.03.03
[Dreamhack] - PATCH-1 (writeup)  (0) 2022.03.02
DigitalForensic with CTF(ctfd) - 제 친구의 개가 바다에서…(writeup)  (0) 2021.09.04
HackCTF - So easy? (forensics writeup)  (0) 2021.08.24
HackCTF - Question? (forensics write up)  (0) 2021.08.24
    '워게임' 카테고리의 다른 글
    • [Webhacking.kr] - old 58 (writeup)
    • [Dreamhack] - PATCH-1 (writeup)
    • DigitalForensic with CTF(ctfd) - 제 친구의 개가 바다에서…(writeup)
    • HackCTF - So easy? (forensics writeup)
    HackHiJack
    HackHiJack
    $ whoami HHJ

    티스토리툴바