CVE-2025-59681
Executive Summary
CVE-2025-59681 is a critical SQL injection vulnerability affecting Django’s ORM methods QuerySet.annotate(), QuerySet.alias(), QuerySet.aggregate(), and QuerySet.extra(). The flaw allows an attacker to inject arbitrary SQL through column aliases when a specially crafted dictionary is passed as **kwargs to these methods. The vulnerability is specific to MySQL and MariaDB backends due to how these databases handle column aliases in SQL queries.
The attack vector is network-based, requires no authentication, and has low complexity. Successful exploitation could lead to unauthorized data access, data manipulation, or denial of service. The EPSS score is 0.0%, indicating low exploitation activity in the wild, but the severity remains high due to the widespread use of Django.
This record — and 170,000+ others — are available via the ValtersIT API. One endpoint replaces five: NVD + GitHub CVE + CISA KEV + EPSS + Nuclei + Exploit-DB, unified.
No signup required
Supply Chain & Package Security
This vulnerability affects the Django Python package, which is distributed via PyPI. Organizations using Django must verify their dependency versions and update immediately. The supply chain risk is elevated because Django is a foundational component in many web applications, and a compromised ORM can lead to cascading failures across the stack.
CVSS Breakdown & Threat Level
- Attack Vector (AV): Network (N) – Exploitable remotely.
- Attack Complexity (AC): Low (L) – No special conditions required.
- Privileges Required (PR): None (N) – No authentication needed.
- User Interaction (UI): None (N) – No user action required.
- Scope (S): Unchanged (U) – Impact confined to the database.
- Confidentiality (C): Low (L) – Limited data exposure.
- Integrity (I): Low (L) – Limited data modification.
- Availability (A): Low (L) – Potential for denial of service.
Threat Level: High (7.1) – Exploitation can lead to SQL injection, a classic and well-understood attack pattern.
Deep Dive & Mechanics
The vulnerability arises from insufficient sanitization of column aliases in Django’s ORM when using MySQL or MariaDB. The **kwargs passed to annotate(), alias(), aggregate(), and extra() are processed as column aliases. If an attacker controls the keys of the dictionary, they can inject SQL syntax that is not properly escaped.
For example, a malicious dictionary like {"col_name OR 1=1--": Value}` could be used to break out of the alias context and execute arbitrary SQL. The issue is specific to MySQL/MariaDB because these databases allow backticks in aliases, which Django does not fully escape.
The vulnerable code path is in django/db/models/query.py where the alias is directly interpolated into the SQL query without proper quoting or parameterization.
Vulnerable vs. Patched Code
Vulnerable Code (Django < 4.2.25):
# In QuerySet.annotate() or similar
def annotate(self, *args, **kwargs):
# ...
for alias, value in kwargs.items():
# Directly uses alias in SQL without escaping
query.add_annotation(value, alias, is_summary=False)
Patched Code (Django >= 4.2.25):
# In QuerySet.annotate() or similar
def annotate(self, *args, **kwargs):
# ...
for alias, value in kwargs.items():
# Sanitize alias to prevent SQL injection
safe_alias = self._sanitize_alias(alias)
query.add_annotation(value, safe_alias, is_summary=False)
The patch introduces a _sanitize_alias() method that strips or escapes dangerous characters, particularly backticks and SQL keywords.
Exploitation & Lab Setup
Red Team
Prerequisites:
- Django application using MySQL or MariaDB backend.
- An endpoint that accepts user-controlled keys for ORM methods (e.g., a search API that passes user input as
**kwargs).
Exploit Payload:
# Example payload for annotate()
payload = {
"col` OR 1=1--": Value(),
"legit_field": Value()
}
queryset.annotate(**payload)
Lab Setup:
- Deploy a vulnerable Django application (e.g., version 4.2.24) with MySQL.
- Create a view that accepts JSON input and passes it to
annotate(). - Send a POST request with the malicious dictionary.
- Observe SQL injection in database logs.
Proof of Concept (PoC):
curl -X POST http://target/api/endpoint \
-H "Content-Type: application/json" \
-d '{"col` OR 1=1--": "value", "legit": "value"}'
Blue Team
Detection:
- Monitor database logs for unusual SQL queries containing backticks or
ORclauses in alias positions. - Use WAF rules to block requests with suspicious key names in JSON payloads.
Mitigation:
- Immediately upgrade Django to patched versions.
- Implement input validation on all user-controlled dictionary keys.
- Use parameterized queries for all ORM operations.
Indicators of Compromise (IOCs)
- Network: HTTP requests with JSON payloads containing backticks or SQL keywords in key names.
- Database: SQL queries with injected
ORorUNIONclauses in alias positions. - Logs: Django error logs showing
OperationalErrororProgrammingErrorrelated to SQL syntax.
Example IOC (Database Log):
SELECT ... AS `col` OR 1=1--` FROM ...
Detection Engineering
YARA Rule
rule CVE_2025_59681_Django_SQLi {
meta:
description = "Detects SQL injection attempts targeting Django ORM alias vulnerability"
author = "Valters IT"
date = "2025-04-10"
reference = "CVE-2025-59681"
strings:
$s1 = /annotate\(.*\*\*kwargs/
$s2 = /alias\(.*\*\*kwargs/
$s3 = /aggregate\(.*\*\*kwargs/
$s4 = /extra\(.*\*\*kwargs/
$s5 = /`.*OR.*--/
condition:
any of ($s1, $s2, $s3, $s4) and $s5
}
Sigma Rule
title: Django ORM SQL Injection via Column Alias
id: 7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d
status: experimental
description: Detects SQL injection attempts against Django ORM methods using malicious column aliases
author: Valters IT
date: 2025/04/10
references:
- https://nvd.nist.gov/vuln/detail/CVE-2025-59681
logsource:
category: application
product: django
detection:
selection:
event: "SQL injection attempt"
method: "annotate|alias|aggregate|extra"
payload|contains: "`"
condition: selection
falsepositives:
- Legitimate use of backticks in column names (rare)
level: high
Suricata Rule
alert http $HOME_NET any -> $EXTERNAL_NET any (
msg:"CVE-2025-59681 Django ORM SQL Injection Attempt";
flow:to_server,established;
content:"POST"; http_method;
content:"annotate"; http_client_body;
content:"`"; http_client_body;
content:"OR"; http_client_body;
classtype:attempted-admin;
sid:1000001;
rev:1;
)
Remediation & Mitigation
Immediate Actions:
- Upgrade Django to version 4.2.25, 5.1.13, or 5.2.7.
- If immediate upgrade is not possible, implement a WAF rule to block requests containing backticks in JSON keys.
- Review all code that passes user input to
annotate(),alias(),aggregate(), orextra().
Long-term Measures:
- Enforce strict input validation on all dictionary keys.
- Use Django’s built-in
Value()andF()expressions instead of raw aliases. - Conduct regular security audits of ORM usage patterns.
Patch Verification:
pip show django | grep Version
# Expected: 4.2.25, 5.1.13, or 5.2.7
Valters IT
Securing Digital Frontiers