Skip to content

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 load

pickletools.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.load demanding a Loader argument is the API warning you in the signature.
  • Model weights: safetensors, or torch.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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.