Safeguard
Security Guides•

Is Python pickle safe? What to use for untrusted data

Python pickle is not safe for untrusted data because loading it can run code. Here is what the docs recommend: JSON, signing, and restricted unpicklers.

Safeguard Security Team
4 min read

No. Python's pickle module is not safe for data you do not fully trust, because a crafted pickle can run arbitrary code while it is being loaded. The Python documentation says to unpickle only data you trust. For anything that crosses a trust boundary, use a data format such as JSON.

Why loading a pickle can run code

A pickle is not a data file in the way JSON is. It is a small program for rebuilding objects. Part of that program is a "reduce value": a callable plus the arguments to call it with. When you call pickle.loads, Python runs that callable.

The Python docs show the effect with a short byte string that makes os.system run an echo command during loading. Nothing in the pickle format limits which callable it names. That is why the docs say never to unpickle data that could have come from an untrusted source or that could have been tampered with.

Where untrusted pickles hide

Developers rarely think "I am loading attacker data." The pickle usually arrives through something that looks internal:

  • A cache or session store that other services can write to.
  • A message queue between workers.
  • A model file or dataset downloaded from a public hub.
  • A file a user uploads and a background job later opens.

The test is simple. Ask who could have written the bytes. If the answer includes anyone you would not give a shell on that server, treat it as untrusted.

Three defenses, and what each one covers

Switch formats. The docs state that safer formats such as JSON may be more appropriate for untrusted data, and that deserializing untrusted JSON does not in itself create an arbitrary code execution vulnerability. The cost is that JSON represents only a subset of Python types and no custom classes. For most APIs and queues, that limit is a feature.

Sign the data. The docs suggest signing with hmac if you need to know the data was not changed. Signing proves that your own code produced the bytes. It does not make unpickling safe if the signing key leaks or if the signer is a system you do not control.

import hmac, hashlib, pickle

def loads_signed(blob, key):
    tag, payload = blob[:32], blob[32:]
    expected = hmac.new(key, payload, hashlib.sha256).digest()
    if not hmac.compare_digest(tag, expected):
        raise ValueError("signature mismatch")
    return pickle.loads(payload)

Restrict what can be loaded. Subclass pickle.Unpickler and override find_class so only a short allowlist of globals is permitted. The docs include an example that allows a handful of builtins such as range and set. They also warn you to be careful about what you allow. Opening up a broad module defeats the point.

Looking at a suspicious pickle without running it

If you need to inspect an unknown pickle, the docs point to python -m pickletools, which does not execute the pickle bytecode. Running python -m pickle on it is not the same thing.

A practical rule

Use pickle only for data that never leaves a boundary you control: a temporary file your own process wrote and reads back, for example. For anything stored, queued, cached across services, downloaded or uploaded, pick a data format and validate it against a schema. If you must accept pickles from elsewhere, combine signing with a narrow allowlist and treat it as a risk you have accepted on purpose.

Safeguard's dependency scanning and reachability analysis can show which libraries in your tree load serialized data, which helps you find the call sites worth reviewing. You can try a free scan at gold.safeguard.sh/scan. See also secure coding checklist: dangerous calls by language.

Quick check

Is a pickle safe if it comes from my own database?

Only if nothing else can write to that database. If another service, a user action or a compromised account can insert rows, the pickle is untrusted in practice.

Does HMAC signing make pickle safe?

It protects against tampering by outsiders. It does not help if the key is exposed or the signing system is itself compromised.

Sources

Last reviewed: 19 October 2026.

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.