Sub topic 5
Why loading a pickle can run code
This chapter assumes you can read basic Python, including classes and special methods like __init__. It also assumes you know that a model file stores trained weights. You have seen that pickle is a stack-based instruction stream. Here you will see how that design lets a file you load run code you never wrote.
Pickle is a recipe, not just data
A pickle file does not store a finished object. It stores instructions that tell the unpickler how to rebuild the object. Some of those instructions import a name from a module and call it.
Pickle needs this for ordinary reasons. A datetime, a set, or a custom class instance cannot be stored as raw bytes. The pickle has to say "import datetime.datetime, call it with these arguments." The instruction that does the calling is also the instruction an attacker uses.
How `__reduce__` works
When Python pickles an object, it asks the object how to rebuild itself by calling __reduce__. The method returns a tuple. Its first two items are a callable and a tuple of arguments. At load time the unpickler runs callable(*args) and uses the result as the object.
Here is a legitimate use:
import pickle
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __reduce__(self):
# Rebuild by calling Point(x, y) at load time.
return (Point, (self.x, self.y))
restored = pickle.loads(pickle.dumps(Point(3, 4)))
print(restored.x, restored.y) # 3 4The unpickler does not check that the callable has anything to do with the object being rebuilt. It accepts any importable callable. That includes print, eval, exec, os.system, and subprocess.Popen.
This example is harmless but shows the mechanism:
import pickle
class Payload:
def __reduce__(self):
# Tells pickle to call print(...) when the data is loaded.
return (print, ("this ran during pickle.loads",))
data = pickle.dumps(Payload())
pickle.loads(data) # prints the message: loading executed a function callThe call happens inside pickle.loads. The code that loads the data never calls print itself. A malicious file would name a more dangerous callable and pass it attacker-chosen arguments. Anyone can write such a file, because __reduce__ is a normal method that the attacker controls when creating the file.
What happens inside the unpickler
Two opcodes do the work. The first pushes a reference to a global name onto the stack. In protocol 4 and later this is typically STACK_GLOBAL, and older protocols use GLOBAL. The unpickler resolves the name by calling its find_class(module, name) method. This imports the module and returns the attribute.
The second is REDUCE. It pops an argument tuple and a callable off the stack, calls the callable with those arguments, and pushes the result.
import pickle
import pickletools
class Payload:
def __reduce__(self):
return (print, ("hello",))
data = pickle.dumps(Payload())
pickletools.dis(data) # disassembles the opcodes without executing themThe disassembly lists a global reference to builtins print, then the string "hello", then a tuple opcode, then REDUCE. Exact opcodes vary by protocol version, but the global lookup followed by REDUCE is always there. pickletools.dis only reads the bytes. It never imports or calls anything, so it is safe to run on a file you do not trust.
It is not just `__reduce__`
A common first reaction is to look for a way to block __reduce__. That does not fix the problem, because the file never has to contain a class with __reduce__. The attacker writes the opcodes directly, with a script that assembles bytes by hand. The opcode stream is the attack surface.
Other opcodes expand it:
BUILDsets an object's state. It calls__setstate__if the class defines one, so a class already on the system can run code.NEWOBJandOBJcreate instances of classes by calling__new__or__init__.INSTandGLOBALimport arbitrary names.
So the risk is not one dangerous method. The format lets the file choose which importable functions run and what arguments they get. The Python documentation says plainly that unpickling untrusted data is insecure. This is how the format is designed to work, so no patch will remove it.
Gotchas that make this hard to spot
The payload can run before any error. The unpickler executes REDUCE as it reads the stream. If the file is corrupt later on, or the final object is the wrong type, load raises an exception. The code has already run by then.
The result can look normal. A malicious callable can run its side effect and then return a real object. For example, a wrapper can run a command and return a real tensor. Your model loads, your tests pass, and nothing looks wrong.
Importing is enough for some attacks. Resolving a global imports a module, and a module's top-level code runs on import. Even a callable that does nothing harmful pulls in whatever module the file names.
Many loaders hide a pickle. These all can unpickle data:
pickle.load,pickle.loadspandas.read_picklejoblib.loadnumpy.load(..., allow_pickle=True)torch.loadon a legacy checkpoint, depending on version and argumentsshelveanddill
A file named .pt, .pth, .bin, or .joblib may be a pickle. The extension does not tell you what loading will do.
Scanning is a weak control. A blocklist of names like os.system can be bypassed. There are many ways to reach a shell from importable Python, and attackers can use the standard library itself to find one. An allowlist is stronger, and the chapter on restricting the unpickler covers it.
What the attacker gets
The code runs with the privileges of the process that loads the file. In ML work that process often has real access:
- cloud credentials in environment variables or instance metadata
- API tokens for model hubs and experiment trackers
- SSH keys and source code on a workstation
- GPUs and training data on a shared cluster
Loading a downloaded checkpoint in a notebook is equivalent to running a script a stranger sent you. Treat it with the same care.
A short checklist
- Ask where the file came from and whether you trust that source and the path it took to you.
- Before loading a pickle-based file, disassemble it with
pickletools.disand look for unexpected globals. - Prefer formats that store only data. Later chapters cover safetensors, GGUF, and ONNX.
- If you must load a pickle, load it in an isolated environment with no credentials.
Review
Exercise
A teammate says, "I will make my loader safe by refusing any pickle whose classes define _reduce_." Give two reasons this does not work.
Show answer
First, the attacker does not need a class with _reduce. They can write the opcodes (a global lookup followed by REDUCE) directly into the file, so the loader never sees a class. Second, other opcodes such as BUILD, NEWOBJ, and OBJ can also trigger code, for example through setstate_ or constructors of classes already installed. The risk comes from the unpickler calling importable names chosen by the file, not from one method.
Exercise
You downloaded a file named weights.bin and want to know whether it would call anything dangerous when loaded, without loading it. Which function do you use, and what do you look for in its output?
Show answer
Use pickletools.dis on the file's bytes. It disassembles the opcodes without importing or calling anything. Look for GLOBAL or STACK_GLOBAL entries that name modules and functions with nothing to do with model weights, such as os, subprocess, builtins eval or exec, followed by REDUCE, which calls them.