IT/Wargame

[Web hacking] simple_sqli

kykyky 2024. 7. 7. 09:31
#!/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)

 

소스코드 분석

/:
index.html 렌더링

/login: 
form에 userid, userpassword 입력하면 ->
이를 db에 query하여, 이 response에서 userid가 admin이면 -> flag 보여줌 

 

exploit

# userid == "admin"이도록 하는 방법

쿼리문은

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

이다.

 

{userid}에는 일단 admin을 넣고, 

우리가 모르는 userpassword에 대한 조건을 무력화하기 위해 

admin 뒤에 "을 넣어 userid 조건을 끝낸 뒤 

--를 붙여 그뒤를 무력화시킨다.

 

# 최종 exploit

userid에

admin"--

userpassword에는 아무거나 입력한다.  

 

그러면 최종 쿼리는  

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

 

'IT > Wargame' 카테고리의 다른 글

[Web Hacking] command-injection-1  (2) 2024.07.08
[Web Hacking] Mango  (0) 2024.07.07
[Web hacking] csrf-2  (0) 2024.07.06
[Web Hacking] csrf-1  (2) 2024.07.05
[Web Hacking] xss-2  (0) 2024.07.03