Insecure Deserialization: How a Serialized Blob Becomes Remote Code Execution
When an application rebuilds objects from untrusted serialized data, attacker-crafted gadget chains can run code during deserialization itself. Here is how object injection leads to RCE, and why data-only formats are the fix.
SelfSec Team 8 min read
Part 1 of 5From the Insecure Deserialization series
At a glance
CWE-502- Interpreter
- Object deserializer and the classes it can instantiate
- Required condition
- Untrusted bytes reach a deserializer that lets the data choose which types to build.
- Potential impact
- Remote code execution, authentication bypass, privilege escalation or denial of service.
- Primary defense
- Accept only data-only formats bound to explicit types; never deserialize untrusted native object streams.
Safe practice: use benign proof only, in a disposable local lab or on a system you are explicitly authorized to test.
On this page
Serialization turns an in-memory object into a stream of bytes you can store or send; deserialization rebuilds the object from those bytes. Insecure deserialization happens when an application reconstructs objects from data an attacker controls without checking its type or integrity. The danger is that deserialization is not a passive copy — for many formats, reconstructing the object runs real code. A carefully crafted blob can therefore turn into remote code execution the moment it is parsed.
This makes it one of the highest-severity bugs on the web: a single deserialized cookie or API field can hand an attacker the server. The OWASP Top 10:2025 lists deserialization of untrusted data (CWE-502) under A08 Software or Data Integrity Failures. This post shows how a trusted serialized blob becomes object injection and RCE, and how to stop feeding untrusted data to a deserializer.
The mental model: who decides which types get built?
Every deserializer answers one question: which classes may the incoming bytes create? When the application decides, the bytes are data. When the bytes decide, the attacker is choosing code to run.
| Format and configuration | What the incoming bytes control | Risk with untrusted input |
|---|---|---|
| JSON bound to a declared DTO | Values for fields you declared | Ordinary input validation |
JSON with embedded type names (Json.NET TypeNameHandling, fastjson autoType) |
Which class to instantiate | Attacker-chosen types and gadgets |
Native object streams (Java serialization, PHP serialize, pickle, Ruby Marshal, BinaryFormatter) |
The whole object graph and its classes | Code runs during reconstruction |
YAML with language tags (PyYAML unsafe loaders, Ruby YAML.unsafe_load) |
Arbitrary objects and constructor calls | Code runs during loading |
Validating the object after it has been rebuilt comes too late: in the bottom three rows, the dangerous methods have already run by the time your code sees the result.
How it happens
The root cause is treating a serialized blob from a cookie, parameter or API body as if it were safe data. A common shape is a "remember me" or session feature that stores object state on the client and rehydrates it on the next request:
import pickle, base64 @app.route("/load") def load(): blob = base64.b64decode(request.cookies.get("state")) state = pickle.loads(blob) return f"Welcome back, {state.username}"
The developer assumes the cookie still holds the object the server wrote. But it is sent by the client, so the attacker can replace it with any serialized payload they like — and pickle.loads will reconstruct whatever that payload describes, executing the type's reconstruction logic in the process.
A concrete attack
Python's pickle invokes a method during reconstruction, which an attacker can repurpose to run a shell command. They build a malicious object, serialize it, and drop it into the state cookie:
import pickle, base64, os class Exploit: def __reduce__(self): return (os.system, ("id > /tmp/pwned",)) payload = base64.b64encode(pickle.dumps(Exploit())).decode()
When the server calls pickle.loads on that cookie, it does not just create an object — it executes os.system("id > /tmp/pwned") on the host. The attacker has gone from "I can set a cookie" to "I run commands on your server."
The same idea spans ecosystems, using gadget chains — sequences of methods already present in the app's libraries that, wired together, reach a dangerous sink:
Java: ObjectInputStream.readObject on an Apache Commons gadget chain
PHP: unserialize() triggering __wakeup / __destruct magic methods
.NET: BinaryFormatter, or Json.NET with TypeNameHandling and a $type gadget
fastjson: an @type / autoType directive that loads an attacker-named class
Node.js: node-serialize evaluating a _$$ND_FUNC$$_ function string
Ruby: Marshal.load or YAML.unsafe_load on a Gem gadget chain
The platform posts go deeper on Java, PHP, Python and .NET.
The bytes were never just data. For these formats, deserializing them is execution — the attacker is not exploiting a parser bug, they are using the deserializer exactly as designed, on input it should never have trusted.
When nothing comes back: blind deserialization
Most deserialization sinks never echo the rebuilt object, and a gadget that runs a command rarely changes the response. An authorized tester proves the sink instead with a payload whose only side effect is a lookup of a unique hostname on an assessment-owned out-of-band listener. For fastjson, an @type directive naming a JDK class that resolves its argument is enough:
{"@type": "java.net.Inet4Address", "val": "deser-check.oob.example"}
A DNS query for that unique name shows the server built the type the payload named and acted on its value. The same approach works with a PyYAML tag or a node-serialize function that performs a lookup, which confirms the sink without running anything that changes the host.
What an attacker gains
Because the payload runs inside the application process, the impact is severe:
- Remote code execution — arbitrary commands on the server, the most common outcome.
- Authentication bypass and privilege escalation — forging objects that represent a logged-in or admin user.
- Denial of service — crafted objects that exhaust memory or CPU on parse.
- Full server compromise — RCE typically leads to data theft, lateral movement and persistence.
Where deserialization hides
Serialized state turns up wherever an application hands an object to a client or another system and expects it back: session and "remember me" cookies, hidden form fields and ASP.NET ViewState, base64 values in API bodies, JSON documents that carry $type or @type keys, message queues, cache entries and file imports. A Java serialized stream starts with the bytes AC ED, which base64 encodes as rO0AB; a PHP serialized object looks like O:4:"User":.... Spotting those shapes in traffic is often the quickest way to find a sink.
The fix: don't deserialize untrusted input; use data-only formats
The only fully reliable rule is to never deserialize data from an untrusted source with a format that can instantiate arbitrary types. Replace native serialization with a data-only format like JSON, parsed into a known schema with explicit fields:
import json @app.route("/load") def load(): try: data = json.loads(request.cookies.get("state") or "{}") except json.JSONDecodeError: abort(400) username = data.get("username") if isinstance(data, dict) else None if not isinstance(username, str) or not username.isalnum(): abort(400) return f"Welcome back, {username}"
JSON parsing produces plain strings, numbers and lists — never an arbitrary object whose construction runs code. In .NET, System.Text.Json behaves the same way when you bind to a declared type, which ASP.NET Core minimal APIs do for you:
app.MapPost("/orders", (OrderRequest order) => order.Quantity is > 0 and <= 100 ? Results.Accepted() : Results.BadRequest()); public sealed record OrderRequest(string Sku, int Quantity);
System.Text.Json only creates the type you declared, and polymorphism is opt-in through an explicit [JsonDerivedType] list. Where a codebase uses Json.NET, keep TypeNameHandling at its default of None. BinaryFormatter cannot be made safe at all; since .NET 9 the in-box implementation throws on use.
When a Java service cannot drop native serialization yet, install an allowlist filter with resource limits on the stream before the first readObject:
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
"maxdepth=5;maxrefs=1000;maxbytes=65536;com.example.dto.*;!*");
try (ObjectInputStream in = new ObjectInputStream(input)) {
in.setObjectInputFilter(filter);
if (!(in.readObject() instanceof OrderDto order)) {
throw new InvalidObjectException("Unexpected type");
}
process(order);
}
The trailing !* rejects every class the pattern did not allow, so a gadget class fails before it is constructed; list any JDK collection types your DTOs need explicitly rather than allowing whole modules. A filter narrows the attack surface but does not make untrusted native deserialization safe, so treat it as a bridge to a data-only format, and set the jdk.serialFilter property as a JVM-wide backstop.
Reinforce it with a few principles: keep client-held state minimal and sign it (e.g. an HMAC) so it cannot be tampered with; if a binary format is unavoidable, enforce a strict type allowlist so only expected classes can be instantiated and disable dangerous features like fastjson autoType; and use yaml.safe_load in Python and YAML.safe_load in Ruby rather than their unsafe loaders. Treat every serialized blob crossing a trust boundary as hostile.
Fixes that do not hold
- Base64-encoding or compressing the blob: encoding hides the format from casual inspection, not from an attacker who can decode it.
- Blocklisting known gadget classes: new chains appear in common libraries, and a blocklist only covers the ones already published.
- Checking the type after deserializing: the gadget's methods run during reconstruction, before any cast or
instanceofcheck. - Catching the exception: a payload that fails to produce the expected type has usually already done its work.
- Signing with a leaked or default key: an HMAC or ViewState MAC protects nothing when the key ships in source code or a sample configuration.
- Relying on a WAF: serialized payloads can be encoded, compressed or wrapped in formats a filter does not unpack.
A developer review checklist
- Inventory deserializer calls:
readObject,XMLDecoder,unserialize,pickle.loads, unsafe YAML loaders,Marshal.load,BinaryFormatter, Json.NETTypeNameHandling, fastjsonautoTypeand node-serialize. - Replace them with data-only formats bound to explicit, validated types.
- Keep session state on the server and give the client an opaque identifier.
- Authenticate any state that must round-trip through the client before parsing it.
- Where native formats remain, apply allowlist filters and size limits, and remove unused libraries that carry known gadgets.
- Run deserializing services with least privilege and restricted outbound network access.
References
- OWASP Top 10:2025 — A08 Software or Data Integrity Failures
- OWASP Deserialization Cheat Sheet
- PortSwigger Web Security Academy: Insecure deserialization
- MITRE CWE-502: Deserialization of Untrusted Data
- Oracle Java documentation: Serialization Filtering
- Microsoft Learn: Deserialization risks in use of BinaryFormatter and related types
- Module
- Insecure Deserialization
- How it probes
- Java serialized-stream, PHP serialize(), PyYAML and fastjson markers, plus out-of-band gadget probes for fastjson, Json.NET TypeNameHandling, node-serialize, PyYAML and Ruby YAML, in query, form, JSON and WebSocket values.
- How it confirms
- A deserializer error that is absent from the baseline and a benign control only marks a possible sink; a DNS or HTTP callback to a unique out-of-band host, from the scan or from fastjson, node-serialize and PyYAML confirmation probes, proves the payload was deserialized.
A reflected response alone is not enough to promote a Insecure Deserialization finding. The classical engine has to confirm the behavior before it reaches the report. See the detection engine
Find Insecure Deserialization in your own app
Reading about the class is one thing. SelfSec tests for it against an application you are authorized to assess, and only calls it real when independent evidence agrees.