Insecure Deserialization: Risks and How to Prevent It
Insecure deserialization lets attackers turn untrusted data into arbitrary code execution, and here's how it happens and how to stop it.
Key takeaways
- Insecure deserialization happens when an application rebuilds objects from untrusted bytes, letting a crafted payload run code during the rebuild.
- Native formats such as Java serialization, Python pickle, PHP unserialize and .NET BinaryFormatter are the usual culprits.
- Accept only data-only formats like JSON across trust boundaries, sign anything else, and run deserializers with least privilege.
On this page
Insecure deserialization is when an application rebuilds objects from bytes it did not verify, so an attacker's crafted payload runs code during the rebuild itself. Native deserializers in Java, Python, PHP and .NET invoke constructors and magic methods before your code sees the object. The fix: accept only data-only formats such as JSON across trust boundaries.
Verified against
Python 3.15 pickle docs, .NET 9 BinaryFormatter guidance, against the OWASP Deserialization Cheat Sheet and OWASP Top 10:2025 (A08). Checked October 2026.
The bug lives in the gap between "receive bytes" and "inspect the result". An attacker who controls the input controls which classes get built and which code paths run, and none of your validation logic has executed yet.
What are serialization and deserialization?
Serialization turns an in-memory object (a class instance with fields, methods, and internal state) into a flat sequence of bytes so it can be stored on disk, cached, or sent across a network. Deserialization is the reverse: take that byte stream and reconstruct the original object graph, with its type and internal state intact.
This pattern is everywhere. Session tokens, cached objects, queue payloads, and inter-service RPC calls all lean on serialization formats to move structured data around. Java has ObjectInputStream and Serializable. Python has pickle. PHP has serialize()/unserialize(). .NET has BinaryFormatter. Each one promises the same convenience: hand it an object, get bytes back, and later get the same object back from those bytes.
The convenience is also the problem. Object serialization formats do not just carry data, they carry type information and instructions for rebuilding that type. When the bytes come from a source you do not control, that source decides which classes get instantiated and which code paths run.
Why is deserializing untrusted data dangerous?
A JSON parser reading {"name": "attacker"} can only produce strings, numbers, booleans, arrays, and objects made of those primitives. It has no concept of "now call this method." A native object deserializer is a different animal. To rebuild a Serializable object it has to invoke constructors, setters, and lifecycle hooks (Java's readObject(), Python's __reduce__, PHP's __wakeup() and __destruct()) as part of the reconstruction process, not after it.
A malicious payload does not need to exploit a bug in your business logic at all. It only needs to describe an object whose normal, intended behavior does something dangerous when constructed. Chain a few such objects together (a gadget chain) and the side effects compound into arbitrary command execution, all before your code gets a chance to check whether the deserialized value looks sane. That is why insecure deserialization routinely leads straight to remote code execution rather than something milder like corrupted data.
What does insecure deserialization look like in each language?
- Java:
ObjectInputStream.readObject()on untrusted bytes is the classic entry point. Attackers rarely need a bug in your code; they need one exploitable class already sitting on the classpath (Apache Commons Collections and Spring have both supplied historical gadget chains) and can wire it into a working exploit with public tooling. - Python:
pickle.loads()on attacker-supplied data is explicitly unsafe. Python's pickle format can embed a__reduce__call that runs any importable function, includingos.system, at load time. - PHP:
unserialize()on user input has produced years of PHP object injection (POI) bugs, typically abusing__wakeup()or__destruct()magic methods to trigger file writes, SQL injection, or code execution. - Node.js: the
node-serializepackage'sunserialize()was shown to execute embedded JavaScript via a crafted_$$ND_FUNC$$_prefix in the serialized string, turning a cookie value into remote code execution. - .NET: Microsoft's guidance says
BinaryFormatter"is insecure and can't be made secure", and starting in .NET 9 the in-box implementation throws exceptions on use.SoapFormatter,LosFormatter,NetDataContractSerializerandObjectStateFormattercarry the same risk;System.Text.Json,DataContractSerializerandXmlSerializerare the recommended replacements.
How do attackers exploit deserialization?
The reconnaissance is often boring. Attackers look for base64-looking blobs sitting in cookies, hidden form fields, or URL parameters, then decode them offline to check for the telltale headers of a serialized object (Java's aced0005 magic bytes, PHP's O:8:"classname" pattern, a pickled opcode stream). Once they confirm the format, they rarely need to hand-craft an exploit from scratch. Tools like ysoserial for Java generate ready-made gadget-chain payloads for dozens of known-vulnerable library combinations, and equivalent tooling exists for PHP and .NET. Insecure deserialization had its own entry in the OWASP Top 10 2017 as A8. The 2021 edition folded it into "Software and Data Integrity Failures", and the current OWASP Top 10:2025 keeps it there as A08 "Software or Data Integrity Failures", with CWE-502 (Deserialization of Untrusted Data) listed and an insecure-deserialization attack scenario spelled out. The underlying problem, trusting bytes to describe their own safe reconstruction, applies beyond object graphs.
How do you prevent insecure deserialization?
The first fix is architectural: never feed data from an untrusted source into a native, unrestricted deserializer. If a value crosses a trust boundary (a user's browser, an external API, another team's queue), treat it as hostile input.
Prefer data-only formats for anything crossing that boundary. JSON, once parsed with a standard library parser, produces plain data structures with no notion of arbitrary type instantiation or method invocation. That single property closes off the whole class of gadget-chain attacks, which is why most modern APIs standardized on JSON over the wire instead of native object serialization.
# Unsafe: pickle reconstructs arbitrary Python objects,
# running __reduce__ during the load itself.
import pickle
def handle_request(request_data):
obj = pickle.loads(request_data) # attacker-controlled code path
return obj
# Safer: JSON only ever produces plain data structures.
import json
def handle_request(request_data):
obj = json.loads(request_data) # dict/list/str/int/bool/None only
return obj
If you genuinely need to move rich objects across a trust boundary, sign the payload and verify that signature before deserialization runs, not after. An HMAC or similar integrity check means a tampered payload gets rejected at the door, before any bytes reach the deserializer. Python's own pickle docs suggest exactly this with the hmac module:
import hashlib, hmac, os, pickle
KEY = os.environ["CACHE_HMAC_KEY"].encode() # injected from your secret store
def dumps_signed(obj) -> bytes:
body = pickle.dumps(obj)
return hmac.new(KEY, body, hashlib.sha256).digest() + body
def loads_signed(blob: bytes):
sig, body = blob[:32], blob[32:]
expected = hmac.new(KEY, body, hashlib.sha256).digest()
if not hmac.compare_digest(sig, expected):
raise ValueError("signature mismatch, refusing to unpickle")
return pickle.loads(body) # only bytes we signed ourselves reach here
Signing only proves the bytes came from someone holding the key. If that key leaks, or if the signed data was built from attacker input, you are back to unpickling hostile bytes. Keep whatever deserialization library you use patched, since most gadget chains depend on a specific vulnerable class being reachable. And run deserializing processes with least privilege, so a gadget chain that slips through lands in a low-permission process instead of one that can read secrets or reach production systems.
None of this is exotic. It is the same trust-boundary discipline behind the rest of application security best practices: validate at the edge, prefer the least powerful format for the job, and assume anything you did not generate yourself is hostile. For the wider set of risks this bug sits among, see the OWASP Top 10 explained.
Questions people ask
Is JSON deserialization always safe?
Plain JSON parsing is safe from gadget chains because it only yields strings, numbers, booleans, arrays and maps. The risk returns when a library maps JSON to arbitrary types named in the payload. OWASP's cheat sheet calls out Json.NET: keep TypeNameHandling set to None. The same applies to YAML: use the safe loader, never the full one, on untrusted input.
Is pickle safe if I sign it with HMAC?
Signing makes pickle safe against tampering, not against bad data you signed yourself. Python's documentation recommends hmac when you must confirm data was not modified, and OWASP lists signing as a language-agnostic mitigation. The check has to run before pickle.loads(), the key must live in a secret store, and the signed content must originate inside your system, never from user input.
Where is insecure deserialization in the OWASP Top 10 2025?
It sits under A08:2025 "Software or Data Integrity Failures", the same slot it held in 2021 under a slightly different name. The category page lists CWE-502, Deserialization of Untrusted Data, and walks through an insecure-deserialization attack scenario. Before 2021 it had its own entry, A8 in the 2017 list.
The call we'd make
Default to JSON or another data-only format for anything crossing a trust boundary, full stop. If a native deserializer has to touch external input, put a signature check in front of it and keep the process it runs in locked down, because gadget chains are a solved problem for attackers and an ongoing one for everyone still calling pickle.loads() or unserialize() on data they did not generate themselves.
Sources
Cite this article
Kiril Urbonas (2026). Insecure Deserialization: Risks and How to Prevent It. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/insecure-deserialization-explained
[Insecure Deserialization: Risks and How to Prevent It](https://www.devopsness.com/blog/insecure-deserialization-explained) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)
More from DevOps
Explore more articles in this category
Chaos Engineering: What We Actually Run as Game Days
How we'd run a quarterly chaos game day. The scenarios that tend to surface real problems, the ones that rarely do, and the operational discipline that makes the practice pay back.
Dependency Scanning and SCA: A Practical Guide
A practical look at how SCA scanning finds vulnerable dependencies, cuts CVE noise, and where SAST, DAST, and IAST fit into CI/CD.
Multi-Arch Docker Builds with Buildx: One Image, Every Platform
Our M-series laptops built arm64, our CI built amd64, and prod pulled whichever tag won the race. Buildx and a manifest list ended the chaos.
You might have missed
Evergreen posts worth revisiting.