Vulnerability class

Insecure deserialization in Python

Insecure deserialization is a flaw where a program rebuilds Python objects from bytes an attacker controls, and the rebuilding itself runs attacker-chosen code, before the program ever looks at the result.

CWE
CWE-502
OWASP
A08:2025 Software or Data Integrity Failures
Tag
unsafe deserialization, critical impact
On this page

How it shows up in Python

pickle is the common case, because it is convenient and because its danger is not obvious. Loading a pickle is not parsing data: the format can name a callable and the arguments to call it with, and pickle.loads() makes that call while rebuilding the object. So any value the program unpickles can run code, and this cookie-backed session store is remote code execution:

import base64
import pickle
from flask import request

def load_session():
    raw = base64.b64decode(request.cookies["session"])
    return pickle.loads(raw)

The attacker controls the cookie, so the attacker controls what gets rebuilt, and a malicious pickle runs its payload the moment loads() is called. Nothing downstream can save it, because the damage is done during the load. The fix is a format that only carries data. For a session, use a signed token so a value the server did not issue is rejected before it is parsed:

import json
from itsdangerous import URLSafeSerializer, BadSignature
from flask import request, abort

serializer = URLSafeSerializer(app.secret_key, salt="session")

def load_session():
    try:
        return serializer.loads(request.cookies["session"])
    except (BadSignature, KeyError):
        abort(400)

itsdangerous serializes with JSON and signs the result, so untrusted bytes are rejected at the signature check and never deserialized into live objects. The same rule applies to the near neighbours:

  • PyYAML. yaml.load(data) with the plain Loader, or yaml.unsafe_load(data), can construct arbitrary Python objects, exactly like pickle. Use yaml.safe_load(data), which builds only standard scalars, lists and dicts.
  • jsonpickle. jsonpickle.decode() reconstructs arbitrary classes from JSON, so it is unsafe on untrusted input even though the wire format looks like plain JSON. Use json.loads() when the data is data.
  • json with hooks. json.loads() alone is safe. json.loads(data, object_hook=...) runs your hook on every object, so an object_hook that instantiates classes by name reintroduces the problem.
  • marshal. marshal.loads() is for trusted .pyc data and makes no safety guarantee on untrusted bytes.

Why it is hard to see

  • First-party, so no advisory. The dangerous call is pickle.loads() in your own code. A dependency scanner only knows published CVEs in packages, so a first-party deserialization bug maps to nothing it tracks.
  • The gadget materializes at load time. The payload is data, not source, and it only becomes a call during loads(). A static analyzer reading the source sees a load, not the code the load will run.
  • The behaviour is a normal function call. Endpoint and behavioural tools key on what a process does after the fact. Code reached through deserialization runs as an ordinary call inside the interpreter, with far less for them to key on, and es-python can stop it before the call happens.
  • Serialized state between internal services. Two back-end services exchange pickled objects over a queue with no HTTP request in sight, so request-scoped tools never inspect it.

What the es-python event looks like

es-python reports untrusted data reaching a deserializer, at the call: pickle loads and pickle load, marshal loads, yaml unsafe load for an unsafe PyYAML loader, object hook for json.loads() with a hook set, and unsafe deserialization for jsonpickle. The pickle and marshal sinks carry the rce impact tag; the others carry unsafe deserialization. yaml.safe_load() and a plain json.loads() are not instrumented as deserialization sinks, so correct code is silent.

Deserialization is the one class here EyalSec never suppresses on the value. For an injection it can sometimes prove the untrusted characters could not break out of the statement; a serialized blob has no such safe form, because any byte can be part of the instruction that runs code. So an unsafe deserialization event always means attacker-controlled bytes reached a loader that can execute them. With network data, it is graded Critical.

Under a Raise rule, pickle.loads() raises a RuntimeError before the bytes are processed, so the embedded payload does not run.

How to fix and prevent it

  1. Keep pickle away from client data, cookies, caches you do not fully trust, and files an attacker could write. Treat pickle as a format between code you control on both ends.
  2. Use data formats for data: json for structured values, yaml.safe_load() for YAML, a schema library such as Pydantic to validate the result.
  3. For signed state like sessions, use a signed serializer (itsdangerous, a signed JWT) so forged data is rejected before it is parsed.
  4. Keep any object_hook or object_pairs_hook from instantiating classes by name from untrusted input.
  5. In Report mode, treat any deserializer event on a network or file source as a priority: unlike most classes, there is no benign version of this flow.

Classification

Insecure deserialization is CWE-502, Deserialization of Untrusted Data. OWASP maps CWE-502 to A08:2025 Software or Data Integrity Failures in the Top 10 for 2025.

Questions people ask

The questions that come up on forums and in reviews about this class, each answered in a few sentences.

Is pickle safe if I sign the data?

Signing protects the bytes in transit, so a pickle you serialized yourself and verify with an HMAC before loading cannot be swapped by an attacker who lacks the key. It does nothing once the key leaks, nothing for a service that signs attacker-supplied objects, and nothing if any code path loads an unsigned copy. Python's own documentation says to unpickle only data you trust, and a signature is one way to establish that trust, not a replacement for a data-only format.

Which Python formats are safe to load from untrusted input?

Formats that carry data and never instructions: json.loads() without an object hook, yaml.safe_load(), MessagePack, CBOR and Protocol Buffers rebuild values, not arbitrary objects. pickle, marshal, shelve, yaml.load() with an unsafe loader and jsonpickle can all run code while loading. For machine-learning models, prefer a weights-only format such as safetensors over a pickled model file.

How do I find every pickle.loads in a running app?

Run the application with es-python and switch on the sources that feed it, such as the network and files, and every call to pickle.loads(), pickle.load(), marshal.loads() or an unsafe YAML loader that receives untrusted bytes is reported with the stack trace, including calls hidden inside a cache backend, a task queue or a session store. Deserialization events are never suppressed, because no byte sequence can be proven harmless. A Raise rule stops the load before the bytes are processed.

Watch for Insecure deserialization in your own code

es-python runs your Python application unchanged and reports when untrusted data reaches the operation, with where the data came from and the line that used it. Ask to see it on your own application.

EyalSec Pricing Docs Security Research Vulnerabilities Play Security glossary About Contact עברית Login Get started Protect my Python app