A vulnerability in Django's Trunc() and Extract() database functions could allow an attacker to execute arbitrary SQL commands. This vulnerability was discovered in Django 3.2 before 3.2.14 and 4.0 before 4.0.6.
The vulnerability is caused by improper string processing when executing SQL for the arguments of the Trunc() and Extract() functions. By specifying the request parameters as is in the kind argument of Trunc() or the lookup_name argument of Extract(), there is a risk that arbitrary SQL commands can be executed.
Attack PoC: An attacker could exploit this vulnerability by crafting a malicious URL that contains a specially crafted request parameter. When a user visits this URL, the Django application would execute the arbitrary SQL command that is specified in the request parameter. This could allow the attacker to access unauthorized data or delete the database.
app/models.py: Define a model in the app. Make the migrations and run them to create a table in the database.
app/views.py: Create the views which will lookup in the database using the passed query parameter by the user. This filters the year numbers in the start_datetime column of ExploitTest that are the same as the year, month, day, hour, minute, second, etc. of end_datetime. SQL Injection vulnerability may be triggered from here.
app/urls.py: Map the endpoint with the views functions.
Test the exploit: To verify that the attack succeeds, use the PG_SLEEP instruction to see if there is a delay in the time the response is returned.
Normal URL:
Exploit URL:
Since arbitrary SQL statements can be executed, dangerous attacks such as database deletion are possible.
Mitigation: The vulnerability has been fixed in Django 3.2.14 and 4.0.6. If you are using an older version of Django, you should upgrade to a patched version as soon as possible.
In addition to upgrading, you can also take the following steps to mitigate the risk of this vulnerability:
Use a web application firewall (WAF) to block malicious traffic.
Keep your operating system and other software up to date.
Use strong passwords and authentication methods.
Educate your users about security risks.
Reference:
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-34265
https://www.djangoproject.com/weblog/2022/jul/04/security-releases/