The Django Software Foundation has released emergency security patches addressing two significant vulnerabilities affecting all supported versions of the popular Python web framework. These flaws, ranging from high to moderate severity, could enable attackers to execute SQL injection attacks against PostgreSQL databases or launch denial-of-service attacks that crash application servers through resource exhaustion.
Django powers millions of websites worldwide, including high-profile platforms from Instagram and Mozilla to The Washington Post and NASA. The framework’s widespread adoption makes these vulnerabilities particularly concerning for the global web development community. Security updates are now available in Django versions 5.2.9, 5.1.15, and 4.2.27, and immediate patching is strongly recommended for all Django-based applications.
Vulnerability Summary
Two distinct security flaws have been identified in Django’s core functionality, each presenting unique risks to application security and availability:
| CVE ID | Vulnerability Type | Severity | CVSS Score | Affected Component |
|---|---|---|---|---|
| CVE-2025-13372 | SQL Injection | HIGH | 8.1 | FilteredRelation class (PostgreSQL) |
| CVE-2025-64460 | Denial of Service (DoS) | MODERATE | 5.3 | XML Serializer (getInnerText method) |
Affected Django Versions
These vulnerabilities impact a wide range of Django versions, requiring coordinated patching efforts across the Django ecosystem:
| Django Version Branch | Vulnerable Versions | Patched Version | Support Status |
|---|---|---|---|
| Django 5.2.x | 5.2.0 – 5.2.8 | 5.2.9 | Active Support |
| Django 5.1.x | 5.1.0 – 5.1.14 | 5.1.15 | Active Support |
| Django 4.2.x (LTS) | 4.2.0 – 4.2.26 | 4.2.27 | Long-Term Support |
| Django 6.0 (RC) | Release Candidates | Pull latest commits | Pre-Release |
| Main Branch | Development builds | Pull latest commits | Development |
CVE-2025-13372: SQL Injection via FilteredRelation (HIGH Severity)
Technical Overview
The most critical vulnerability identified in this security release is a SQL injection flaw affecting Django applications that utilize PostgreSQL databases. This high-severity issue exists within the FilteredRelation class, specifically in how Django handles column aliases when constructing database queries.
SQL injection remains one of the most dangerous web application vulnerabilities, consistently ranking in the OWASP Top 10. This particular flaw allows attackers to break out of the intended SQL query structure and inject arbitrary SQL commands that the database will execute with the application’s privileges.
Vulnerable Code Pattern
The vulnerability manifests when developers use dictionary expansion with QuerySet.annotate() or QuerySet.alias() methods. The following code patterns are vulnerable:
# Vulnerable pattern - using dictionary expansion
user_filters = {
'active_orders': FilteredRelation('orders', condition=Q(orders__status='active'))
}
queryset = User.objects.annotate(**user_filters)
# Vulnerable pattern - dynamic alias creation
dynamic_aliases = {
request.GET.get('filter_name'): FilteredRelation('related_model')
}
queryset = Model.objects.alias(**dynamic_aliases)
Attack Scenario and Exploitation
An attacker can exploit this vulnerability by crafting malicious dictionary keys that contain SQL injection payloads. When these keys are expanded into the query through the **kwargs pattern, Django fails to properly sanitize the column alias names, allowing SQL code injection.
| Attack Phase | Attacker Action | Impact |
|---|---|---|
| 1. Reconnaissance | Identify Django application using PostgreSQL with filtered relations | Target identification |
| 2. Payload Crafting | Create malicious dictionary with SQL injection in key names | Exploit preparation |
| 3. Injection | Submit crafted payload through application input that reaches annotate/alias | SQL code injection |
| 4. Execution | Malicious SQL executes with application database privileges | Database compromise |
| 5. Data Exfiltration | Extract sensitive data, modify records, or escalate privileges | Complete compromise |
Potential Impact of SQL Injection
Successful exploitation of this SQL injection vulnerability can lead to severe consequences:
- Unauthorized Data Access: Attackers can bypass authentication and authorization controls to read sensitive information including user credentials, personal data, financial records, and proprietary business information
- Data Manipulation: Modification or deletion of database records, including user accounts, transaction history, audit logs, and critical business data
- Authentication Bypass: Direct access to user accounts by extracting password hashes or manipulating authentication logic within the database
- Privilege Escalation: Elevation of attacker’s privileges to administrator level by modifying user role assignments in the database
- Database Server Compromise: In PostgreSQL environments, attackers may execute operating system commands through database functions like
COPY TO PROGRAMor other server-side extensions - Lateral Movement: Use compromised database credentials to pivot to other systems and databases within the infrastructure
Real-World Risk Assessment
| Risk Factor | Assessment | Justification |
|---|---|---|
| Exploitability | MEDIUM | Requires specific code patterns and user-controlled input reaching vulnerable methods |
| Attack Complexity | MEDIUM | Attacker needs understanding of Django ORM and PostgreSQL SQL syntax |
| Privileges Required | LOW | May only need basic application access or public-facing input vectors |
| User Interaction | NONE | Attack can be fully automated without victim interaction |
| Scope | CHANGED | Impact extends beyond application to database server and potentially infrastructure |
| Confidentiality Impact | HIGH | Complete database contents can be extracted |
| Integrity Impact | HIGH | All database records can be modified or deleted |
| Availability Impact | HIGH | Database can be made unavailable through destructive operations |
CVE-2025-64460: Denial of Service via XML Serializer (MODERATE Severity)
Technical Overview
The second vulnerability affects Django’s XML serialization functionality, specifically the django.core.serializers.xml_serializer.getInnerText() method. This moderate-severity flaw stems from algorithmic complexity issues in how the serializer processes XML text nodes.
The vulnerability represents a classic algorithmic complexity attack, where specially crafted input forces the application to perform computational operations that scale poorly, consuming excessive CPU and memory resources.
Root Cause Analysis
The getInnerText() method collects text content from XML nodes through repeated string concatenation operations. In Python, string concatenation creates new string objects for each operation, as strings are immutable. When processing deeply nested XML structures with numerous text nodes, this approach leads to quadratic time complexity (O(n²)).
# Vulnerable pattern (simplified)
def getInnerText(node):
text = ""
for child in node.childNodes:
if child.nodeType == Node.TEXT_NODE:
text = text + child.data # Creates new string object each time
else:
text = text + getInnerText(child) # Recursive concatenation
return text
Attack Mechanics
An attacker can exploit this vulnerability by crafting XML input with specific characteristics designed to maximize computational overhead:
| XML Structure Characteristic | Effect on Processing | Resource Impact |
|---|---|---|
| Deep Nesting Levels | Increases recursive call depth and concatenation operations | CPU cycles, call stack memory |
| Numerous Text Nodes | Each text node triggers string concatenation | Memory allocation, CPU time |
| Large Text Content | Each concatenation copies all previous string data | Memory bandwidth, allocation overhead |
| Mixed Element/Text Patterns | Maximizes number of concatenation operations | CPU time, temporary object creation |
Denial of Service Impact
When the XML serializer processes maliciously crafted input, the computational complexity leads to severe resource exhaustion:
- CPU Saturation: Processing threads consume 100% CPU for extended periods, preventing legitimate request processing
- Memory Exhaustion: Repeated string object creation fills available memory, potentially triggering out-of-memory conditions
- Thread Pool Depletion: Long-running requests block worker threads, preventing new connection handling
- Application Unresponsiveness: Server becomes unable to respond to legitimate user requests
- Service Degradation: Even if the server doesn’t crash completely, response times become unacceptable
- Cascading Failures: Load balancers may remove unresponsive servers, increasing load on remaining instances
Attack Complexity Analysis
| Attack Characteristic | Level | Description |
|---|---|---|
| Skill Level Required | LOW | Simple XML structure generation requires minimal expertise |
| Resource Requirements | MINIMAL | Single request can cause significant impact |
| Detection Difficulty | MEDIUM | Appears as legitimate XML processing, hard to distinguish from valid traffic |
| Mitigation Complexity | LOW | Patching resolves the issue completely |
| Impact Severity | MODERATE-HIGH | Can cause complete service outage with minimal attacker effort |
Vulnerable Application Scenarios
Understanding which applications are most at risk helps prioritize patching efforts:
| Application Type | CVE-2025-13372 Risk | CVE-2025-64460 Risk | Priority |
|---|---|---|---|
| REST APIs using PostgreSQL | HIGH | LOW | CRITICAL |
| Data Import/Export Systems | MEDIUM | HIGH | CRITICAL |
| Public-Facing Web Applications | HIGH | MEDIUM | HIGH |
| Admin Dashboards | MEDIUM | MEDIUM | HIGH |
| Integration Endpoints (XML-based) | LOW | HIGH | HIGH |
| Content Management Systems | HIGH | MEDIUM | HIGH |
| E-commerce Platforms | HIGH | HIGH | CRITICAL |
| Internal Tools (Limited Access) | MEDIUM | LOW | MEDIUM |
Immediate Mitigation Steps
Step 1: Identify Affected Applications
Organizations must first inventory all Django applications and determine which versions are in use:
# Check Django version python -m django --version # Or within application python manage.py --version # Check via Python python -c "import django; print(django.get_version())"
| Step | Action | Command/Method |
|---|---|---|
| 1 | List all Django projects in infrastructure | Review deployment documentation, check server configurations |
| 2 | Determine Django version for each project | Run version check commands on production servers |
| 3 | Identify database backend (PostgreSQL check) | Review settings.py DATABASES configuration |
| 4 | Check for XML serializer usage | Search codebase for django.core.serializers.xml_serializer |
| 5 | Assess FilteredRelation usage patterns | Code review for annotate/alias with dictionary expansion |
| 6 | Prioritize applications based on exposure | Public-facing > Internal > Development |
Step 2: Apply Security Updates
Update all affected Django installations to the patched versions:
# Update via pip pip install --upgrade Django==5.2.9 # For 5.2.x users pip install --upgrade Django==5.1.15 # For 5.1.x users pip install --upgrade Django==4.2.27 # For 4.2.x LTS users # Verify update python -m django --version # For development branch users cd /path/to/django git pull origin main
| Update Phase | Action Items | Validation |
|---|---|---|
| Pre-Update | Create full backups, test in staging environment, review release notes | Backup verification, staging test results |
| Update Execution | Update Django package, update dependencies if needed, clear Python cache | Version confirmation, dependency check |
| Testing | Run automated tests, manual functionality verification, performance testing | Test suite pass, functionality checklist |
| Deployment | Deploy to production, restart application servers, clear application cache | Application startup, health check endpoints |
| Post-Deployment | Monitor error logs, check application metrics, verify security fixes | Log review, metrics dashboard, vulnerability scan |
Step 3: Code Review and Hardening
While patching resolves the vulnerabilities, reviewing code for vulnerable patterns improves overall security posture:
For SQL Injection (CVE-2025-13372):
- Avoid Dictionary Expansion with User Input: Never use
**kwargspatterns where dictionary keys come from untrusted sources - Whitelist Allowed Aliases: Define explicit allowed annotation names rather than accepting arbitrary user input
- Input Validation: Validate and sanitize any user input before using it in query construction
- Use Parameterized Queries: Rely on Django ORM’s built-in parameterization rather than string formatting
# SECURE: Explicit annotation names
if filter_type == 'active':
queryset = User.objects.annotate(
active_orders=FilteredRelation('orders', condition=Q(orders__status='active'))
)
elif filter_type == 'completed':
queryset = User.objects.annotate(
completed_orders=FilteredRelation('orders', condition=Q(orders__status='completed'))
)
# AVOID: User-controlled dictionary keys
user_input = {'field_name': FilteredRelation(...)}
queryset = Model.objects.annotate(**user_input) # Vulnerable pattern
For DoS (CVE-2025-64460):
- Input Size Limits: Implement maximum size limits for XML input
- Complexity Limits: Restrict XML nesting depth and total element count
- Request Timeouts: Configure appropriate timeouts for XML processing operations
- Rate Limiting: Implement rate limits on endpoints accepting XML input
- Alternative Serialization: Consider JSON serialization where XML is not strictly required
Detection and Monitoring
Implement monitoring to detect potential exploitation attempts:
| Indicator Type | What to Monitor | Detection Method |
|---|---|---|
| SQL Injection Attempts | Database error logs with SQL syntax errors | Log aggregation, SIEM alerts |
| Unusual Query Patterns | Complex queries with unexpected structure | Database query logging, anomaly detection |
| CPU Spikes | Sustained high CPU usage on application servers | System monitoring, APM tools |
| Memory Growth | Rapid memory consumption during XML processing | Memory profiling, resource monitoring |
| Long Request Times | XML processing requests taking excessive time | Application performance monitoring |
| XML Size Anomalies | Unusually large or deeply nested XML payloads | Input validation logging, WAF rules |
| Failed Requests | Increased error rates or timeouts | Error rate monitoring, health checks |
Defense in Depth Recommendations
Beyond patching, implement multiple security layers to protect Django applications:
| Security Layer | Implementation | Benefit |
|---|---|---|
| Web Application Firewall | Deploy WAF with rules for SQL injection and XML attacks | Blocks common attack patterns before reaching application |
| Database Access Controls | Use least-privilege database accounts, read-only where possible | Limits damage from successful SQL injection |
| Input Validation | Validate all user input at application entry points | Prevents malicious data from reaching vulnerable code |
| Rate Limiting | Implement per-IP and per-user rate limits | Mitigates DoS attacks and automated exploitation |
| Security Monitoring | Deploy SIEM, IDS/IPS, and application monitoring | Enables rapid detection and response to attacks |
| Database Activity Monitoring | Monitor and alert on unusual database queries | Detects SQL injection exploitation attempts |
| Resource Limits | Configure memory and CPU limits for processes | Prevents single request from consuming all resources |
| Regular Security Audits | Conduct periodic code reviews and vulnerability assessments | Identifies vulnerabilities before attackers do |
Long-Term Security Best Practices
1. Automated Dependency Management
Implement automated processes for tracking and updating dependencies:
- Use dependency management tools like Dependabot or Renovate
- Configure automated security alerts for vulnerable packages
- Establish regular update schedules with testing protocols
- Maintain inventory of all Django applications and their versions
2. Security-Focused Development Practices
Integrate security throughout the development lifecycle:
- Secure Coding Standards: Establish and enforce coding standards that prevent common vulnerabilities
- Code Review Process: Require security-focused peer review for all code changes
- Static Analysis: Integrate SAST tools into CI/CD pipeline to catch vulnerabilities early
- Dynamic Testing: Perform regular DAST scans on staging and production environments
- Security Training: Provide ongoing security training for development teams
3. Incident Response Preparation
Prepare for potential security incidents:
- Develop and document incident response procedures
- Conduct regular security drills and tabletop exercises
- Maintain up-to-date contact information for security team
- Establish communication protocols for security incidents
- Document rollback procedures for emergency situations
Django Security Resources
Leverage Django’s security ecosystem for ongoing protection:
| Resource | Description | URL |
|---|---|---|
| Django Security Announcements | Official mailing list for security updates | Subscribe via djangoproject.com |
| Django Security Policy | Guidelines for reporting vulnerabilities | docs.djangoproject.com/en/stable/internals/security/ |
| Django Release Notes | Detailed changelog including security fixes | docs.djangoproject.com/en/stable/releases/ |
| OWASP Django Security | Best practices for Django security | owasp.org |
| CVE Database | Official vulnerability tracking | cve.mitre.org |
Conclusion
The discovery of CVE-2025-13372 and CVE-2025-64460 highlights the ongoing importance of proactive security maintenance in Django applications. While Django’s security team has responded quickly with patches, the responsibility for implementing these updates rests with application developers and operations teams.
The SQL injection vulnerability (CVE-2025-13372) represents a critical risk to applications using PostgreSQL, potentially allowing complete database compromise. The DoS vulnerability (CVE-2025-64460), while rated moderate, can still cause significant service disruption with minimal attacker effort.
Organizations running Django applications should treat these updates as high-priority security patches requiring immediate deployment. The combination of widespread Django adoption, relatively straightforward exploitation, and severe potential impact creates an urgent need for rapid response.
Action Summary Checklist:
| Priority | Action Item | Status |
|---|---|---|
| IMMEDIATE | Inventory all Django applications and identify versions | ☐ |
| IMMEDIATE | Update all Django installations to patched versions | ☐ |
| IMMEDIATE | Test updated applications in staging environment | ☐ |
| HIGH | Deploy updates to production systems | ☐ |
| HIGH | Review code for vulnerable patterns (dictionary expansion, XML processing) | ☐ |
| HIGH | Implement monitoring for exploitation attempts | ☐ |
| MEDIUM | Configure WAF rules for SQL injection and XML attacks | ☐ |
| MEDIUM | Review and strengthen input validation | ☐ |
| MEDIUM | Implement rate limiting on XML processing endpoints | ☐ |
| ONGOING | Subscribe to Django security announcements | ☐ |
| ONGOING | Establish automated dependency update processes | ☐ |
Need Help Securing Your Django Applications?
At SiteGuarding, we specialize in comprehensive web application security services including:
- Security Audits: Complete code review and vulnerability assessment for Django applications
- Penetration Testing: Simulated attacks to identify vulnerabilities before malicious actors do
- Patch Management: Managed update services ensuring timely security patch deployment
- 24/7 Monitoring: Continuous security monitoring with real-time threat detection
- Incident Response: Expert assistance during security incidents and breach remediation
- Security Consulting: Strategic guidance on implementing security best practices
Contact our security team at support@siteguarding.com for a free security consultation and learn how we can help protect your Django applications from emerging threats.
