Difficulty: Advanced
What is insecure deserialization, why can it lead to remote code execution, and how do you prevent it?
Insecure deserialization happens when an application takes untrusted bytes, such as a cookie, request body, or message queue payload, and turns them back into live objects using a native serialization format like Java serialization, Python pickle, PHP unserialize or .NET BinaryFormatter. Because these formats can describe arbitrary classes and trigger code during object reconstruction, an attacker can craft a payload that runs commands on the server. The fix is to never deserialize untrusted data with native object formats and to use data-only formats like JSON with strict schemas instead.
Native serializers do more than fill in fields. During deserialization they may:
readObject in Java, __reduce__ in Python pickle, __wakeup and __destruct in PHP, OnDeserialized callbacks in .NET.hashCode while rebuilding collections.An attacker chains these existing, legitimate methods together into a gadget chain that ends in something dangerous, such as Runtime.exec(). They do not need to upload new code; they reuse classes already in your dependencies. Tools like ysoserial generate ready-made chains for common Java libraries, and the Apache Commons Collections gadgets caused widespread RCE across Java app servers such as WebLogic, JBoss and Jenkins.
.pkl or older PyTorch checkpoint can execute code. PyTorch 2.6 changed torch.load to default to weights_only=True for this reason, and formats like safetensors avoid it entirely.yaml.load with an unsafe loader in PyYAML can construct arbitrary Python objects. Use yaml.safe_load.node-serialize package allowed RCE via serialized functions (CVE-2017-5941).Even without RCE, deserialization bugs can enable privilege escalation (changing role in a serialized object) or DoS through deeply nested or huge object graphs.
ObjectInputFilter, JEP 290) with an allowlist of expected classes, and remove unused gadget libraries.BinaryFormatter; it is obsolete and was removed from .NET 9. Use System.Text.Json.In the OWASP Top 10 this falls under A08 Software and Data Integrity Failures; it was a standalone category (A8) in the 2017 edition.
import pickle, os, json
class Exploit:
# pickle calls __reduce__ to learn how to rebuild the object
def __reduce__(self):
return (os.system, ("echo pwned: $(whoami)",))
payload = pickle.dumps(Exploit()) # attacker sends these bytes
# VULNERABLE: server 'restores' a cart from a cookie
pickle.loads(payload) # runs the shell command
# SAFE: data-only format plus validation
cart = json.loads('{"items": [{"sku": "A12", "qty": 2}]}')
assert isinstance(cart["items"], list)
Unpickling calls os.system with attacker-chosen arguments. JSON only produces dicts, lists, strings and numbers, so there is nothing to execute.
import java.io.*;
public class SafeRead {
public static Object read(byte[] data) throws Exception {
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
"com.example.cart.Cart;com.example.cart.Item;java.util.ArrayList;"
+ "maxdepth=5;maxrefs=1000;maxbytes=65536;!*"
);
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
in.setObjectInputFilter(filter); // reject everything not listed
return in.readObject();
}
}
}
The trailing !* rejects any class not explicitly allowed, which blocks gadget classes. Limits on depth, references and size also prevent DoS payloads.
Insecure Deserialization, Gadget Chains, Remote Code Execution, Java Serialization, Python pickle