Lesson 9 of 20 · 18m
Serialization Is a Trust Boundary
pickle.loads is eval in a serialization costume — __reduce__ emits arbitrary callables, ML model files are pickles, and safetensors exists because of it.
pickle.loads(data) is eval wearing a serialization format. Pickle is not a data format — it is bytecode for a small stack machine whose job is constructing objects, and __reduce__ lets any object emit an arbitrary callable plus arguments for the unpickler to invoke. Feed it bytes an attacker wrote and it runs their function.
import os, pickle
class Evil:
def __reduce__(self):
return (os.system, ("id > /tmp/pwned",))
pickle.loads(pickle.dumps(Evil())) # runs `id` during the loadpickletools.dis(payload) disassembles a pickle so you can see the opcodes — c (global lookup), ( (mark), S (string), R (reduce: call the callable). Nothing in that instruction set asks your consent. loads executes it.
The wrong mental model
"Pickle is Python's JSON." JSON is a grammar for values — strings, numbers, arrays, objects — and json.loads cannot reach a function. Pickle is a program that describes objects by their constructors. The difference is not readability or size; it is that unpickling is execution.
shelve is pickle underneath. marshal is the interpreter's own internal format — never for data exchange. yaml.load without a Loader spent years defaulting to arbitrary object construction: PyYAML <5.4's FullLoader had CVE-2020-14343, a code-execution hole via python/object/new, and yaml.safe_load exists precisely because the full loaders were never safe on hostile input.
The real-world receipts
ML model files are pickles. torch.load calls pickle by default; joblib.dump for scikit-learn is pickle. In early 2024 JFrog found roughly a hundred malicious models on Hugging Face whose pickle payloads ran code on load() — download a fine-tuned model, inherit someone's shell. picklescan exists as a standalone scanner for exactly this, and Hugging Face integrated scanning because the risk was routine, not theoretical. safetensors — a data-only tensor format built specifically to kill the pickle dependency — is what HF pushes for weights for the same reason. PyTorch 2.6 flipped torch.load to weights_only=True by default, which restricts the pickle opcodes it will run.
None of this is exotic. Any time your app calls pickle.loads on bytes that crossed a trust boundary — an upload, a cache file a lower-privilege process can write, a queue payload, a model from a stranger — you have installed eval on user input under a friendlier name.
The boundary that holds
- On the wire and at rest:
json,orjson,msgspec— pure data, no code path. Binary or speed: protobuf, msgpack. - YAML config:
yaml.safe_load, always.yaml.loaddemanding aLoaderargument is the API warning you in the signature. - Model weights:
safetensors, ortorch.load(..., weights_only=True)when you must. - Internal persistence where you control both ends and nothing untrusted can touch the file: pickle is fine. The line is who wrote the bytes, not the format itself.
- "I signed the pickle" is the only legitimate way to ship one — the signature, not the format, is what makes it safe.
Why pickle exists at all
Pickle serializes arbitrary object graphs — circular references, nested classes, even functions. cloudpickle and dill push further: closures and interactively-defined functions. That is the feature Celery, Dask, and Ray build on — the task you submit is pickled and shipped to workers, which means the broker is the trust boundary. Whoever can write to your Redis queue or task topic controls what your workers execute. Securing the queue is securing the code path.
Even JSON has footguns worth naming: json.dumps emits NaN/Infinity by default (allow_nan=True), which strict parsers on other languages reject — a quiet interop bug. json.dumps returns str, not bytes. And json.loads is safe from code execution, not from resource exhaustion — a 400 MB JSON body is still a 400 MB allocation.
Treat pickle.loads the way you treat subprocess.run(shell=True) on user input: the bytes are a program. If you would not let the source run code, do not load their pickle.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Free-Threaded Python, Measured: Threads Finally Scale, and Your Unlocked Counter Finally Breaks
Python 3.14 made the no-GIL build officially supported, and 3.15 kept going. I ran the same CPU-bound job on standard and free-threaded builds of both: threads went from slower-than-serial to 1.9x faster, and a counter that never lost an update under the GIL lost 70% of them without it.
What is Python? Enterprise, Data Science, and the Backend of the Web
Python runs Instagram, Dropbox, Netflix, Spotify, and Reddit. It trains the models that power modern AI. It processes petabytes of data in enterprise pipelines. And I ignored it for years because I thought it was just for academics. Here is what changed my mind.
What Python 3.13 Shipped
The first release of Python 3.13 is now here as a Beta Release. This article is a rundown of all of the important changes and features that are being released in Python 3.13, along with what they mean for Python Developers. Please remember that this can change between
What Python 3.11 Actually Changed
The Python Programming Language releases a new version every year, with a feature-locked beta release in the first half of the year and the final release toward the end of the year. The feature set for Python 3.11 has just been finalized, with a beta version available for testing.