SQL injection in JSONField KeyTransform
A JSONField key transform in Django's ORM did not properly quote the key name passed to .values(), so a crafted key containing a double quote broke out of the SQL string literal. An attacker who could control that key name could inject SQL into the generated query.
- Triaged in 8 days
- Fixed in 8 months
- Disclosed after 14 months
Hi Django team
The vulnerability is in: https://github.com/django/django/blob/main/tests/model_fields/test_jsonfield.py#L427 I created a function and added it to the "test_jsonfield.py" to explain the vulnerability (POC).
def test_sqli(self):
# say a to get value b
# say b to get value c
# say " for syntax error in sql
user_input = "b"
NullableJSONModel.objects.create(value_custom={"a": "b"})
NullableJSONModel.objects.create(value_custom={"b": "c"})
qs = NullableJSONModel.objects.filter(value_custom__isnull=False).values(
"value_custom__" + user_input,
).annotate(
count=Count("id"),
)
for i in qs:
v = i["value_custom__" + user_input]
if v:
print(v)
to execute the below code i did:
python runtests.py model_fields.test_jsonfield.TestQuerying.test_sqli
When I execute above function with user_input = "beeeee\"" in the code, I get sql syntax error.
The sql code that get executed is:
SELECT COUNT("model_fields_nullablejsonmodel"."id") AS "count", (CASE WHEN JSON_TYPE("model_fields_nullablejsonmodel"."value_custom", ?) IN ('true','null','false') THEN JSON_TYPE("model_fields_nullablejsonmodel"."value_custom", ?) ELSE JSON_EXTRACT("model_fields_nullablejsonmodel"."value_custom", ?) END) AS "value_custom__beeeee"" FROM "model_fields_nullablejsonmodel" WHERE "model_fields_nullablejsonmodel"."value_custom" IS NOT NULL GROUP BY 2
Impact
if user input get into .values( the user will able to create sql injection attack.
I hope you have best day :)
Eyal
Context
Django's JSONField lets you store JSON documents in a database column and query into them using key transforms. When you write something like value_custom__a in a queryset, Django builds a KeyTransform that compiles down to database-specific JSON functions: on SQLite that means JSON_TYPE and JSON_EXTRACT, on other backends the equivalent. The key you pass after the double underscore becomes part of the generated SQL.
The report points at the test file that exercises this behaviour, specifically the querying tests around line 427 of tests/model_fields/test_jsonfield.py, and shows that a key transform built from user-controlled input can break out of the SQL it is placed into.
Setup
No special accounts, roles or third-party tools are involved. The researcher worked inside the Django source tree, using the project's own test runner against the model_fields test app. The proof of concept is a new test method added to test_jsonfield.py, run with:
python runtests.py model_fields.test_jsonfield.TestQuerying.test_sqli
The model used is NullableJSONModel, which the existing tests already define, with a JSON field called value_custom.
Finding it
The key portion of a lookup such as value_custom__<key> is turned into SQL. The key is concatenated into the query rather than bound as a parameter. The test method below was written to demonstrate this, using a variable user_input to stand in for attacker-controlled input.
Exploitation
Step 1: Build the proof of concept
The researcher added the following method to test_jsonfield.py:
def test_sqli(self):
# say a to get value b
# say b to get value c
# say " for syntax error in sql
user_input = "b"
NullableJSONModel.objects.create(value_custom={"a": "b"})
NullableJSONModel.objects.create(value_custom={"b": "c"})
qs = NullableJSONModel.objects.filter(value_custom__isnull=False).values(
"value_custom__" + user_input,
).annotate(
count=Count("id"),
)
for i in qs:
v = i["value_custom__" + user_input]
if v:
print(v)
The comments spell out the intended behaviour of the key: asking for a returns the value b, asking for b returns the value c, and a " is expected to produce a syntax error in the SQL. Two rows are created with different JSON documents. The key is concatenated onto the field name ("value_custom__" + user_input) and passed to .values(), then the queryset is annotated with Count("id") and iterated.
Step 2: Run with a normal key
With user_input = "b" the key transform resolves to the JSON key b, which the comments say should return the stored value c. This establishes the baseline, that the lookup itself works and the key is being placed into the generated SQL.
Step 3: Inject a quote
Changing the value to user_input = "beeeee\"" (a key ending in a double quote) and running the same command produces an SQL syntax error. The statement Django generated for that run is:
SELECT COUNT("model_fields_nullablejsonmodel"."id") AS "count", (CASE WHEN JSON_TYPE("model_fields_nullablejsonmodel"."value_custom", ?) IN ('true','null','false') THEN JSON_TYPE("model_fields_nullablejsonmodel"."value_custom", ?) ELSE JSON_EXTRACT("model_fields_nullablejsonmodel"."value_custom", ?) END) AS "value_custom__beeeee"" FROM "model_fields_nullablejsonmodel" WHERE "model_fields_nullablejsonmodel"."value_custom" IS NOT NULL GROUP BY 2
The important part is the alias at the end of the CASE expression: AS "value_custom__beeeee"". The injected quote closes the identifier early, leaving a stray " in the statement, which is what triggers the syntax error.
Root cause
The report does not describe any code change or the exact compiler path beyond the test file reference.
Impact
As the report puts it: if user input gets into .values(, the user will be able to create an SQL injection attack. The condition is explicit: the application must pass attacker-influenced data as the key in a values() call (or an equivalent lookup that reaches the same key transform). Where that happens, the attacker controls part of the generated SQL statement. The report demonstrates a syntax error as proof of control; it does not show data extraction or any other post-injection outcome.
Fix
Variants to test
- Other key transforms on the same field: try keys containing quotes, parentheses and comment markers in
filter(),annotate()andorder_by()as well asvalues(), and watch the generated SQL for the key appearing outside a placeholder. A positive result is a key that changes the statement's structure or produces a database error that mentions the injected text. - Other backends: the report's statement is SQLite-flavoured (
JSON_TYPE,JSON_EXTRACT). Try the same key on PostgreSQL and MySQL/MariaDB JSON lookups and compare how the key is quoted. A positive result is the same early termination of the identifier or string on any backend. - Nested keys: use the double-underscore chaining that
KeyTransformsupports to see whether each segment is interpolated the same way. A positive result is any segment that escapes its quoting. - Other Django lookups that accept a field-like string from user input, such as ordering and aggregation aliases. A positive result is a quote in the input producing a syntax error in the generated SQL.
Hunting notes
This kind of bug hides where an ORM builds identifiers, aliases or JSON paths from strings rather than binding them as parameters. The signal during recon is any application code that concatenates user input onto a field name before passing it to the ORM, especially in values(), annotate() or order_by(). The report made its case with a minimal test inside the framework's own test suite: a key ending in a quote that produces a syntax error, plus the exact SQL. That is enough to show control over the statement without needing to demonstrate data exfiltration.
What happened, in plain words
Django is a popular toolkit for building websites with the Python programming language. One of its features, called JSONField, lets a website store a bundle of structured data (a JSON document) in a single database column. Think of it like a labelled filing box: instead of one flat value, the box holds many labelled compartments, each with its own value.
Django also lets a developer reach into one of those compartments when querying the database. You write a field name, two underscores, then the compartment name, for example value_custom__a. Django turns that into database instructions that fetch the value stored under the key a.
The researcher found that the compartment name (the part after the double underscore) is pasted directly into the database command as raw text instead of being handed over as a separate, safely wrapped value. If a website lets a visitor influence that compartment name, the visitor can slip extra database syntax into the command. This class of bug is called SQL injection: the attacker changes the meaning of a database query by injecting their own SQL (the language databases speak) into it.
The report proves the problem with a small test inside Django's own codebase. It shows that a key ending in a double quote breaks the generated database command with a syntax error. A syntax error is the database saying "I cannot understand this command", which is evidence that the attacker's text reached the command itself.
Background you need first
A few ideas come up repeatedly, so here they are from zero.
- Database: the place where a website keeps its data permanently, like a very large, very organised spreadsheet that the website's code can ask questions of.
- SQL: the language used to ask those questions. A question like "give me all rows where the value is not empty" is written in SQL.
- Query: one such question sent to the database.
- ORM (Object-Relational Mapper): a layer of code that lets a programmer write queries in their own programming language (here, Python) and translates them into SQL automatically. Django's ORM is the part of Django that does this translation.
- Parameter (bound parameter): a placeholder in a query where a value is slotted in separately, so the database treats it purely as data and never as part of the command's grammar. You can picture it as a blank on a form: whatever you write on the blank stays on the blank and cannot rewrite the rest of the form. In the SQL shown later, these placeholders appear as
?. - String concatenation: gluing pieces of text together, for example
"value_custom__" + user_input. If the second piece is attacker-controlled, the attacker's text becomes part of the final string. This is the opposite of using a parameter. - Identifier: a name inside SQL, such as a column name or an alias (a temporary label for a result). Identifiers are usually wrapped in quote characters so the database knows where the name starts and ends.
- Alias: a temporary name given to a column in a query's output, written with
ASin SQL. - JSON: a text format for structured data, made of keys and values, for example
{"a": "b"}. The keyamaps to the valueb. - JSONField: Django's field type for storing a JSON document in a database column.
- Key transform: Django's mechanism for reaching into a JSON document by key during a query. Writing
value_custom__ameans "the value stored under keyainside thevalue_customfield". - Queryset: Django's representation of a database query that has not necessarily run yet. You build it up with method calls and then read the results.
.values(): a queryset method that says which columns you want back..filter(): a queryset method that says which rows you want..annotate(): a queryset method that adds a computed column to the results, such as a count.- Test runner: a tool that runs automated checks (tests) against code to confirm it behaves as expected. Django ships its own, invoked as
runtests.py. - Proof of concept (POC): a small, minimal demonstration that a suspected problem is real.
Context: where the bug lives
Django's JSONField stores a JSON document in a database column and lets you query into it using key transforms. When you write something like value_custom__a in a queryset, Django builds an internal object called a KeyTransform, which is then translated into database-specific JSON functions. On SQLite (a small, file-based database) those functions are JSON_TYPE and JSON_EXTRACT; other database systems have their own equivalents.
The key you put after the double underscore ends up as part of the generated SQL. That is the crux: a piece of text that a user might control is being treated as part of the database command's grammar rather than as pure data.
The report points at the test file that exercises this behaviour, specifically the querying tests around line 427 of tests/model_fields/test_jsonfield.py, and shows that a key transform built from user-controlled input can break out of the SQL it is placed into.
Setup: what you need to reproduce it
No special accounts, roles or third-party tools are involved. The researcher worked inside the Django source tree (a copy of Django's own code) using the project's own test runner against the model_fields test app. The proof of concept is a new test method added to test_jsonfield.py, run with:
python runtests.py model_fields.test_jsonfield.TestQuerying.test_sqli
Line by line: python runs the Python interpreter; runtests.py is Django's test runner script; the dotted name after it selects one specific test, here the test_sqli method inside the TestQuerying class in the model_fields.test_jsonfield module. Running a single named test keeps the output focused on the demonstration.
The model used is NullableJSONModel, which the existing tests already define, with a JSON field called value_custom. A model in Django is the code that describes a database table; NullableJSONModel is a small table used by the tests, and value_custom is its JSON column.
Finding it
The key portion of a lookup such as value_custom__<key> is turned into SQL. The key is concatenated into the query rather than bound as a parameter.
The test method below was written to demonstrate this, using a variable user_input to stand in for attacker-controlled input. The idea is to swap the value of that one variable and watch what happens to the generated SQL.
Exploitation
Step 1: Build the proof of concept
The researcher added the following method to test_jsonfield.py:
def test_sqli(self):
# say a to get value b
# say b to get value c
# say " for syntax error in sql
user_input = "b"
NullableJSONModel.objects.create(value_custom={"a": "b"})
NullableJSONModel.objects.create(value_custom={"b": "c"})
qs = NullableJSONModel.objects.filter(value_custom__isnull=False).values(
"value_custom__" + user_input,
).annotate(
count=Count("id"),
)
for i in qs:
v = i["value_custom__" + user_input]
if v:
print(v)
Line by line, in plain words:
def test_sqli(self):declares a new test method namedtest_sqli. The test runner picks up methods whose names start withtest_.- The three comment lines spell out the intended behaviour of the key: asking for
areturns the valueb, asking forbreturns the valuec, and a"is expected to produce a syntax error in the SQL. They are the researcher's notes on what each input should do. user_input = "b"sets the variable that stands in for whatever a user might supply. It starts with a harmless value so the baseline can be checked first.NullableJSONModel.objects.create(value_custom={"a": "b"})inserts a row whose JSON document maps keyato valueb.NullableJSONModel.objects.create(value_custom={"b": "c"})inserts a second row whose JSON document maps keybto valuec. Two rows are created with different JSON documents.qs = NullableJSONModel.objects.filter(value_custom__isnull=False)starts building a query over rows where the JSON field is not empty..values(then opens the list of columns to return, and the next line supplies the column name."value_custom__" + user_input,is the heart of the demonstration: the field name and the user input are glued together into one string, which is handed to.values(). This is the concatenation that lets user input become part of the query..annotate(count=Count("id"))adds a computed column namedcountholding the number of rows in each group.- The
forloop walks through the results.i["value_custom__" + user_input]reads the column whose name was built from the same concatenation, andprint(v)shows the value if it is non-empty.
Step 2: Run with a normal key
With user_input = "b" the key transform resolves to the JSON key b, which the comments say should return the stored value c. This establishes the baseline, that the lookup itself works and the key is being placed into the generated SQL.
Step 3: Inject a quote
Changing the value to user_input = "beeeee\"" (a key ending in a double quote) and running the same command produces an SQL syntax error. The statement Django generated for that run is:
SELECT COUNT("model_fields_nullablejsonmodel"."id") AS "count", (CASE WHEN JSON_TYPE("model_fields_nullablejsonmodel"."value_custom", ?) IN ('true','null','false') THEN JSON_TYPE("model_fields_nullablejsonmodel"."value_custom", ?) ELSE JSON_EXTRACT("model_fields_nullablejsonmodel"."value_custom", ?) END) AS "value_custom__beeeee"" FROM "model_fields_nullablejsonmodel" WHERE "model_fields_nullablejsonmodel"."value_custom" IS NOT NULL GROUP BY 2
What this statement is doing, piece by piece:
SELECT COUNT("model_fields_nullablejsonmodel"."id") AS "count"asks the database to count rows and label the resultcount.- The
CASE WHEN ... THEN ... ELSE ... ENDblock is a conditional: it checks the type of the JSON value and either reports the type or extracts the value.JSON_TYPEandJSON_EXTRACTare the SQLite functions that read into a JSON document. - The
?marks are bound parameters: the JSON path arguments are slotted in separately, so the database treats them purely as data. AS "value_custom__beeeee""is the alias, the temporary column label. This is where the key was pasted in as raw text.FROM "model_fields_nullablejsonmodel"names the table, andWHERE ... IS NOT NULLkeeps only rows with a non-empty JSON field.GROUP BY 2groups the results by the second column of the output, which is the computed JSON column.
The important part is the alias at the end of the CASE expression: AS "value_custom__beeeee"". The injected quote closes the identifier early, leaving a stray " in the statement, which is what triggers the syntax error. In everyday terms: the form had proper blanks for some values, but the label at the top of the form was written by hand from the visitor's text, so a quote in that text tore the label apart.
Root cause
The report does not describe any code change or the exact compiler path beyond the test file reference.
Impact
As the report puts it: if user input gets into .values(, the user will be able to create an SQL injection attack. The condition is explicit: the application must pass attacker-influenced data as the key in a values() call (or an equivalent lookup that reaches the same key transform). Where that happens, the attacker controls part of the generated SQL statement. The report demonstrates a syntax error as proof of control; it does not show data extraction or any other post-injection outcome.
Many sites never do that, because keys are usually fixed by the developer. But where a site does, a visitor can reshape the database command, and the researcher's syntax error is the first sign that this is possible.
Fix
Variants to test
If you want to look for similar problems yourself, these are the directions the technical write-up suggests. Each one is a way of asking "does user text reach the SQL grammar somewhere else too?".
- Other key transforms on the same field: try keys containing quotes, parentheses and comment markers in
filter(),annotate()andorder_by()as well asvalues(), and watch the generated SQL for the key appearing outside a placeholder. A positive result is a key that changes the statement's structure or produces a database error that mentions the injected text. - Other backends: the report's statement is SQLite-flavoured (
JSON_TYPE,JSON_EXTRACT). Try the same key on PostgreSQL and MySQL/MariaDB JSON lookups and compare how the key is quoted. A positive result is the same early termination of the identifier or string on any backend. - Nested keys: use the double-underscore chaining that
KeyTransformsupports to see whether each segment is interpolated the same way. A positive result is any segment that escapes its quoting. - Other Django lookups that accept a field-like string from user input, such as ordering and aggregation aliases. A positive result is a quote in the input producing a syntax error in the generated SQL.
Hunting notes
This kind of bug hides where an ORM builds identifiers, aliases or JSON paths from strings rather than binding them as parameters. The signal during recon (the early, exploratory phase of looking for weaknesses) is any application code that concatenates user input onto a field name before passing it to the ORM, especially in values(), annotate() or order_by(). The report made its case with a minimal test inside the framework's own test suite: a key ending in a quote that produces a syntax error, plus the exact SQL. That is enough to show control over the statement without needing to demonstrate data exfiltration.
Glossary
- Annotate: a Django queryset method that adds a computed column, such as a count, to the results.
- Backend: the specific database system Django is talking to, such as SQLite, PostgreSQL or MySQL/MariaDB.
- Bound parameter: a value slotted into a query separately from the command text, so the database treats it purely as data; shown as
?in the SQL here. - Concatenation: gluing pieces of text together into one string.
- Database: the organised store where a website keeps its data.
- Django: a toolkit for building websites in Python.
- Filter: a Django queryset method that selects which rows to return.
- Identifier: a name inside SQL, such as a column name or alias, usually wrapped in quote characters.
- JSON: a text format for structured data made of keys and values.
- JSON_EXTRACT: a SQLite function that pulls a value out of a JSON document.
- JSON_TYPE: a SQLite function that reports the type of a value inside a JSON document.
- Key transform: Django's mechanism for reaching into a JSON document by key during a query, written as
field__key. - KeyTransform: the internal Django object that represents a key transform and is translated into database-specific SQL.
- Metacharacter: a character with special meaning in a language, such as a quote in SQL.
- Model: Django code that describes a database table.
- ORM (Object-Relational Mapper): code that translates queries written in a programming language into SQL.
- Parameterisation: the practice of passing values to a query as bound parameters instead of pasting them into the command text.
- Query: a question sent to a database.
- Recon: the early, exploratory phase of looking for weaknesses in a target.
- SQL: the language used to ask questions of a database.
- SQLite: a small, file-based database system.
- Syntax error: the database saying it cannot understand a command, often a sign that unexpected text reached the command.
- Test runner: a tool that runs automated checks against code; Django's is
runtests.py. - Values: a Django queryset method that says which columns to return.