A critical vulnerability (CVE-2022-28346) has been discovered in Django, impacting versions 2.2 before 2.2.28, 3.2 before 3.2.13, and 4. before 4..4. The vulnerability allows an attacker to inject SQL code via vulnerable QuerySet methods leading to a potential SQL injection attack. This post aims to discuss the vulnerability details, provide code snippets to explain the issue, and offer links to original references.

QuerySet.extra()

These methods are found to be vulnerable to SQL injection attacks due to the way they handle column aliases passed as kwargs. The vulnerability arises when a crafted dictionary is passed as the kwargs parameter with dictionary expansion.

Here's a code snippet explaining the issue

from django.db.models import CharField, Value
from myapp.models import MyModel

# Potentially unsafe user input (e.g., from a query string or form data)
column_alias = "my_col) AS injected_sql --"

# Crafted dictionary with dictionary expansion (**kwargs)
injected_data = {
    f"{column_alias}__{Value('str')}_Val": Value('text', output_field=CharField())
}

# Unsafe use of user-controlled column alias in QuerySet methods
result = MyModel.objects.annotate(**injected_data).aggregate()

In the example above, the potentially unsafe user input column_alias is used to create a crafted dictionary (injected_data) with a crafted key and a legitimate Value object. When this crafted dictionary is passed to the QuerySet methods (annotate, aggregate, or extra), the result can lead to an SQL injection attack.

As a Django developer, it is crucial to ensure that any user input used as column aliases must be properly validated and sanitized before passing it to the aforementioned QuerySet methods.

1. Django Security Advisory
2. CVE-2022-28346 Details
3. Official Django Documentation on QuerySet.annotate()
4. Official Django Documentation on QuerySet.aggregate()
5. Official Django Documentation on QuerySet.extra()

Conclusion

CVE-2022-28346 is a critical vulnerability affecting Django 2.2 before 2.2.28, 3.2 before 3.2.13, and 4. before 4..4. It is essential to understand the implications of this vulnerability and ensure that user inputs are appropriately validated and sanitized before using them as column aliases in QuerySet methods. By doing so, developers can better protect their applications from potential SQL injection attacks.

Timeline

Published on: 04/12/2022 05:15:00 UTC
Last modified on: 06/09/2022 19:15:00 UTC