Critical Django Security Updates: SQL Injection and DoS Vulnerabilities Require Immediate Patching

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 IDVulnerability TypeSeverityCVSS ScoreAffected Component
CVE-2025-13372SQL InjectionHIGH8.1FilteredRelation class (PostgreSQL)
CVE-2025-64460Denial of Service (DoS)MODERATE5.3XML 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 BranchVulnerable VersionsPatched VersionSupport Status
Django 5.2.x5.2.0 – 5.2.85.2.9Active Support
Django 5.1.x5.1.0 – 5.1.145.1.15Active Support
Django 4.2.x (LTS)4.2.0 – 4.2.264.2.27Long-Term Support
Django 6.0 (RC)Release CandidatesPull latest commitsPre-Release
Main BranchDevelopment buildsPull latest commitsDevelopment

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 PhaseAttacker ActionImpact
1. ReconnaissanceIdentify Django application using PostgreSQL with filtered relationsTarget identification
2. Payload CraftingCreate malicious dictionary with SQL injection in key namesExploit preparation
3. InjectionSubmit crafted payload through application input that reaches annotate/aliasSQL code injection
4. ExecutionMalicious SQL executes with application database privilegesDatabase compromise
5. Data ExfiltrationExtract sensitive data, modify records, or escalate privilegesComplete 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 PROGRAM or 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 FactorAssessmentJustification
ExploitabilityMEDIUMRequires specific code patterns and user-controlled input reaching vulnerable methods
Attack ComplexityMEDIUMAttacker needs understanding of Django ORM and PostgreSQL SQL syntax
Privileges RequiredLOWMay only need basic application access or public-facing input vectors
User InteractionNONEAttack can be fully automated without victim interaction
ScopeCHANGEDImpact extends beyond application to database server and potentially infrastructure
Confidentiality ImpactHIGHComplete database contents can be extracted
Integrity ImpactHIGHAll database records can be modified or deleted
Availability ImpactHIGHDatabase 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 CharacteristicEffect on ProcessingResource Impact
Deep Nesting LevelsIncreases recursive call depth and concatenation operationsCPU cycles, call stack memory
Numerous Text NodesEach text node triggers string concatenationMemory allocation, CPU time
Large Text ContentEach concatenation copies all previous string dataMemory bandwidth, allocation overhead
Mixed Element/Text PatternsMaximizes number of concatenation operationsCPU 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 CharacteristicLevelDescription
Skill Level RequiredLOWSimple XML structure generation requires minimal expertise
Resource RequirementsMINIMALSingle request can cause significant impact
Detection DifficultyMEDIUMAppears as legitimate XML processing, hard to distinguish from valid traffic
Mitigation ComplexityLOWPatching resolves the issue completely
Impact SeverityMODERATE-HIGHCan cause complete service outage with minimal attacker effort

Vulnerable Application Scenarios

Understanding which applications are most at risk helps prioritize patching efforts:

Application TypeCVE-2025-13372 RiskCVE-2025-64460 RiskPriority
REST APIs using PostgreSQLHIGHLOWCRITICAL
Data Import/Export SystemsMEDIUMHIGHCRITICAL
Public-Facing Web ApplicationsHIGHMEDIUMHIGH
Admin DashboardsMEDIUMMEDIUMHIGH
Integration Endpoints (XML-based)LOWHIGHHIGH
Content Management SystemsHIGHMEDIUMHIGH
E-commerce PlatformsHIGHHIGHCRITICAL
Internal Tools (Limited Access)MEDIUMLOWMEDIUM

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())"
StepActionCommand/Method
1List all Django projects in infrastructureReview deployment documentation, check server configurations
2Determine Django version for each projectRun version check commands on production servers
3Identify database backend (PostgreSQL check)Review settings.py DATABASES configuration
4Check for XML serializer usageSearch codebase for django.core.serializers.xml_serializer
5Assess FilteredRelation usage patternsCode review for annotate/alias with dictionary expansion
6Prioritize applications based on exposurePublic-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 PhaseAction ItemsValidation
Pre-UpdateCreate full backups, test in staging environment, review release notesBackup verification, staging test results
Update ExecutionUpdate Django package, update dependencies if needed, clear Python cacheVersion confirmation, dependency check
TestingRun automated tests, manual functionality verification, performance testingTest suite pass, functionality checklist
DeploymentDeploy to production, restart application servers, clear application cacheApplication startup, health check endpoints
Post-DeploymentMonitor error logs, check application metrics, verify security fixesLog 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 **kwargs patterns 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 TypeWhat to MonitorDetection Method
SQL Injection AttemptsDatabase error logs with SQL syntax errorsLog aggregation, SIEM alerts
Unusual Query PatternsComplex queries with unexpected structureDatabase query logging, anomaly detection
CPU SpikesSustained high CPU usage on application serversSystem monitoring, APM tools
Memory GrowthRapid memory consumption during XML processingMemory profiling, resource monitoring
Long Request TimesXML processing requests taking excessive timeApplication performance monitoring
XML Size AnomaliesUnusually large or deeply nested XML payloadsInput validation logging, WAF rules
Failed RequestsIncreased error rates or timeoutsError rate monitoring, health checks

Defense in Depth Recommendations

Beyond patching, implement multiple security layers to protect Django applications:

Security LayerImplementationBenefit
Web Application FirewallDeploy WAF with rules for SQL injection and XML attacksBlocks common attack patterns before reaching application
Database Access ControlsUse least-privilege database accounts, read-only where possibleLimits damage from successful SQL injection
Input ValidationValidate all user input at application entry pointsPrevents malicious data from reaching vulnerable code
Rate LimitingImplement per-IP and per-user rate limitsMitigates DoS attacks and automated exploitation
Security MonitoringDeploy SIEM, IDS/IPS, and application monitoringEnables rapid detection and response to attacks
Database Activity MonitoringMonitor and alert on unusual database queriesDetects SQL injection exploitation attempts
Resource LimitsConfigure memory and CPU limits for processesPrevents single request from consuming all resources
Regular Security AuditsConduct periodic code reviews and vulnerability assessmentsIdentifies 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:

ResourceDescriptionURL
Django Security AnnouncementsOfficial mailing list for security updatesSubscribe via djangoproject.com
Django Security PolicyGuidelines for reporting vulnerabilitiesdocs.djangoproject.com/en/stable/internals/security/
Django Release NotesDetailed changelog including security fixesdocs.djangoproject.com/en/stable/releases/
OWASP Django SecurityBest practices for Django securityowasp.org
CVE DatabaseOfficial vulnerability trackingcve.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:

PriorityAction ItemStatus
IMMEDIATEInventory all Django applications and identify versions
IMMEDIATEUpdate all Django installations to patched versions
IMMEDIATETest updated applications in staging environment
HIGHDeploy updates to production systems
HIGHReview code for vulnerable patterns (dictionary expansion, XML processing)
HIGHImplement monitoring for exploitation attempts
MEDIUMConfigure WAF rules for SQL injection and XML attacks
MEDIUMReview and strengthen input validation
MEDIUMImplement rate limiting on XML processing endpoints
ONGOINGSubscribe to Django security announcements
ONGOINGEstablish 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.