TExcelTAD

Insecure Deserialization

Applications turn objects into bytes to store them in cookies, caches, queues and files, and turn the bytes back into objects later. Formats like JSON only carry data. But many languages also have native object serialization (Python's pickle, Java's ObjectInputStream, PHP's unserialize, .NET's BinaryFormatter, Ruby's Marshal) that can describe any object, including which class to build and which methods to call while building it. Deserializing such bytes from an untrusted source lets the sender decide what code runs. In Python this is not a subtle bug: the pickle format contains an instruction to call an arbitrary function, by design. Insecure deserialization falls under A08 Software or Data Integrity Failures in the OWASP Top 10 2025. This lesson shows the mechanism with a payload whose only effect is a print, then the detection signatures and the fixes.

Definitions

  • Serialization / deserialization: object → bytes / bytes → object.
  • Gadget: an existing class in the application or its libraries whose deserialization side effects (constructors, __reduce__, readObject, __wakeup/__destruct in PHP, setters) can be chained into dangerous actions. Java exploits famously chain gadgets from common libraries (the "ysoserial" family); Python doesn't even need gadgets, because __reduce__ names a callable directly.
  • __reduce__: the method pickle uses to learn how to rebuild an object: it returns a callable and its arguments, and pickle.loads calls it.
  • Integrity protection: a MAC (HMAC-SHA256 with a server-side key) or signature over the serialized bytes, so the server only deserializes what it produced itself.

The mechanism: unpickling calls a function

A web app keeps the user's preferences in a cookie as a Base64 pickle, a pattern found in real code because it "just works". The attacker builds their own object whose __reduce__ returns print and a message. Here the callable is print; in an attack it would be os.system or subprocess.Popen, which is exactly why the example stops at print.

python · try it yourself
import base64, pickle

# What the application does
cookie = base64.b64encode(pickle.dumps({"theme": "dark", "lang": "en"})).decode()
print("normal cookie starts with:", cookie[:8], "| decodes to theme =", pickle.loads(base64.b64decode(cookie))["theme"])

# What an attacker sends instead: any object whose __reduce__ names a callable
class Harmless:
    def __reduce__(self):
        return (print, ("!! code chosen by the cookie's author ran during pickle.loads",))

evil_cookie = base64.b64encode(pickle.dumps(Harmless())).decode()
print("attacker cookie starts with:", evil_cookie[:8])
result = pickle.loads(base64.b64decode(evil_cookie))      # the application's line, unchanged
print("pickle.loads returned:", result)

import pickletools
ops = [op.name for op, arg, pos in pickletools.genops(base64.b64decode(evil_cookie))]
print("opcodes:", ops)
normal cookie starts with: gASVIAAA | decodes to theme = dark
attacker cookie starts with: gASVWgAA
!! code chosen by the cookie's author ran during pickle.loads
pickle.loads returned: None
opcodes: ['PROTO', 'FRAME', 'SHORT_BINUNICODE', 'MEMOIZE', 'SHORT_BINUNICODE', 'MEMOIZE', 'STACK_GLOBAL', 'MEMOIZE', 'SHORT_BINUNICODE', 'MEMOIZE', 'TUPLE1', 'MEMOIZE', 'REDUCE', 'MEMOIZE', 'STOP']

The application's code never changed: the same pickle.loads line ran a function chosen by whoever wrote the cookie, before the application could look at the result (which is None, the return value of print). The opcode listing shows why: STACK_GLOBAL loads a callable by module and name, and REDUCE calls it with arguments. Python's documentation is explicit: never unpickle data received from an untrusted or unauthenticated source.

The fixes: data formats, and integrity

The first fix is to store data, not objects: JSON can only produce dicts, lists, strings, numbers, booleans and null, so there is nothing to call. The second, for any format, is to make sure the bytes are the server's own: an HMAC over the payload with a key only the server knows. The example uses a fixed key so the output is stable; real keys come from a secret store.

python · try it yourself
import base64, hashlib, hmac, json

KEY = b"lab-only-cookie-signing-key-32-bytes!!"

def b64(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def unb64(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

def make_cookie(prefs: dict) -> str:
    body = json.dumps(prefs, separators=(",", ":"), sort_keys=True).encode()
    return b64(body) + "." + b64(hmac.new(KEY, body, hashlib.sha256).digest())

def read_cookie(cookie: str) -> dict:
    body_b64, _, sig_b64 = cookie.partition(".")
    body = unb64(body_b64)
    if not hmac.compare_digest(hmac.new(KEY, body, hashlib.sha256).digest(), unb64(sig_b64)):
        raise ValueError("signature mismatch")
    prefs = json.loads(body)
    if set(prefs) - {"theme", "lang"} or prefs.get("theme") not in {"dark", "light"}:
        raise ValueError("unexpected content")
    return prefs

c = make_cookie({"theme": "dark", "lang": "en"})
print("cookie:", c)
print("read:", read_cookie(c))
tampered = b64(b'{"lang":"en","theme":"dark","is_admin":true}') + "." + c.split(".")[1]
for label, value in [("tampered body", tampered), ("pickle payload", "gASVQAAAAAAAAACMCGJ1aWx0aW5zlIwFcHJpbnSUk5Q.AAAA")]:
    try:
        read_cookie(value)
    except (ValueError, json.JSONDecodeError) as e:
        print(f"{label}: rejected ({e})")
cookie: eyJsYW5nIjoiZW4iLCJ0aGVtZSI6ImRhcmsifQ.fjbYdF_WvNhEeXcCZx5lz_LWJSRm3__oIxERLM0Mer8
read: {'lang': 'en', 'theme': 'dark'}
tampered body: rejected (signature mismatch)
pickle payload: rejected (signature mismatch)

The tampered body (with an extra is_admin) fails the signature check, and a pickle blob is rejected the same way, without ever being parsed. Even with a valid signature, the reader validates the content against the expected shape, because a signature proves who made the data, not that it is sensible. Frameworks offer this ready-made: Django's signing module, itsdangerous (Flask), ASP.NET Data Protection.

How insecure deserialization is detected

  • Recognise serialized blobs in cookies, hidden fields, headers, message queues and caches: Python pickle protocol 2+ starts with byte 0x80 (Base64 gA…; protocol 4 typically gASV, protocol 5 gAWV), Java serialization with AC ED 00 05 (Base64 rO0AB), PHP with O:8:"ClassNam":… or a:2:{…}, .NET BinaryFormatter with AAEAAAD/////, Ruby Marshal with 04 08 (Base64 BAh).
  • Code review: pickle.loads, pickle.load, shelve, jsonpickle.decode, yaml.load without SafeLoader (PyYAML), marshal.loads, ObjectInputStream.readObject, unserialize(, BinaryFormatter.Deserialize, Marshal.load, on anything not produced and integrity-checked by the same service. Bandit flags B301 (pickle) and B506 (yaml load); Semgrep and CodeQL have rules for each language.
  • Testing (in scope): replace a recognised blob with a harmless payload whose effect you can observe (a time delay, a DNS lookup to your lab listener) in a test environment.
  • Runtime: unexpected child processes or outbound connections from the process that deserializes, deserialization exceptions naming unexpected classes (Java's InvalidClassException, filter rejections).

How it is fixed

  1. Don't deserialize native objects from untrusted sources. Use JSON (or Protocol Buffers, MessagePack) and build objects explicitly from validated fields.
  2. Sign or MAC anything the client stores and you read back; reject before parsing.
  3. Where native deserialization must stay (legacy Java), apply class allow-lists (ObjectInputFilter / jdk.serialFilter from JEP 290: Java 9+, backported to 8u121 and later updates; a find_class override in Python's Unpickler), and patch libraries with known gadgets. .NET's BinaryFormatter is obsolete, and since .NET 9 its implementation is removed (calls throw PlatformNotSupportedException unless an unsupported compatibility package is added): migrate away.
  4. yaml.safe_load, never yaml.load on input.

Pitfalls

  • Encrypting instead of authenticating: encryption without a MAC (AES-CBC alone) can be tampered with; use authenticated encryption or a MAC.
  • "It's in our Redis/queue, so it's trusted": anyone who can write to the cache (another compromised service, an SSRF to Redis) can plant objects.
  • Signing with a weak or leaked key (SECRET_KEY committed to Git) turns the signature into decoration; rotate and keep keys in a secret store.

Practice

1. A cookie value starts with rO0ABXNy. What is it and what do you check?

Base64 of a Java serialized object (AC ED 00 05 73 72: stream magic, version, TC_OBJECT, TC_CLASSDESC). Check whether the server deserializes it without a signature check or class filter, and which libraries are on its class path; report it even before proving exploitation, because the pattern itself is the risk.

2. Why is the HMAC checked before json.loads and not after?

So untrusted bytes are never parsed at all: a parser bug, a huge or deeply nested document, or a different format can't do anything if the signature check fails first.

Test yourself

Why is pickle.loads on a cookie dangerous?

  1. Pickle is slow
  2. The pickle format can name any callable to be called during loading, so the cookie's author chooses code to run
  3. Pickles are large
  4. Cookies can't hold binary data

In the demo, when did the attacker's print run?

  1. When the app read result.theme
  2. During pickle.loads, before the app could inspect anything
  3. Never
  4. At pickle.dumps on the server

Which Base64 prefix suggests a Java serialized object?

  1. eyJ
  2. gASV
  3. rO0AB
  4. PD94

What does the HMAC on the JSON cookie guarantee?

  1. Confidentiality
  2. That the server produced the bytes (integrity and authenticity), so tampering is rejected before parsing
  3. Short cookies
  4. That the content is sensible