Sub topic 5
Why Loading a Pickle Can Run Code
Assume you know basic Python classes, special methods, model weights, and byte streams. You should also understand that loading a file supplied by someone else is a security boundary.
Python’s pickle module serializes objects into bytes. Serialization turns an in-memory object into a byte stream. Deserialization, or unpickling, reconstructs the object from that stream.
The security problem is that a pickle stream is not limited to passive data. It is a sequence of instructions for a small stack-based virtual machine. The unpickler reads each opcode, places values on its stack, imports referenced objects, and performs operations that rebuild the original object.
`__reduce__` Supplies a Recipe
A class can define __reduce__. This special method returns a callable and its arguments. During unpickling, Python calls that callable to create the object.
The callable does not need to be a constructor. It can be any importable function. This means a malicious object can arrange for a function to run when its pickle is loaded.
The following example is harmless because it only prints a message:
import pickle
class Payload:
def __reduce__(self):
# The unpickler will call print("this ran during pickle.loads").
return (print, ("this ran during pickle.loads",))
data = pickle.dumps(Payload())
print("Before loading")
pickle.loads(data)
print("After loading")The output includes the message between “Before loading” and “After loading”. The call to pickle.loads caused print to run. A malicious payload could select a function with more serious effects, such as modifying files or starting another process.
The important point is that the dangerous behavior occurs during loading, before your program receives the resulting object. Checking the object afterward cannot undo actions that already happened.
Inspecting Instructions Without Loading Them
pickletools.dis displays the opcode stream without executing the pickle. This is useful for triage and education:
import pickle
import pickletools
class Payload:
def __reduce__(self):
return (print, ("hello",))
data = pickle.dumps(Payload())
pickletools.dis(data)Look for operations that reference globals or invoke reductions. Inspection is not a proof of safety. A complex stream can be difficult to analyze, and a callable may hide behavior behind several layers. Treat inspection as a review aid, not as permission to load an untrusted file.
> callout warning > Never call pickle.load or pickle.loads on an untrusted model file. A file ending in .pkl, .pt, or .pth is not safe merely because it has a familiar extension.
The Practical Rule
Only unpickle data from a source you trust, or use a loader that enforces a restricted set of types. For PyTorch checkpoints, weights_only=True is one important defense because it rejects many arbitrary Python objects. It does not replace provenance checks, isolation, or safer data-only formats.
Exercise
Why can __reduce__ make unpickling dangerous?
Show answer
It lets the pickle specify an importable callable and arguments, which the unpickler may invoke during object reconstruction.