Insecure Deserialization in Python and Ruby
You'll learn how dynamic language deserialization libraries can execute arbitrary code when deserializing untrusted data.
The Core Problem
Python and Ruby are dynamically typed languages with powerful serialization libraries that can preserve not just data, but code references and object states. When these libraries deserialize untrusted input, attackers can craft malicious payloads that execute arbitrary code during the deserialization process itself—before your application even touches the data.
Think of it like this: Deserialization is like unpacking a box. In safer formats (like JSON), you only get data—apples, oranges, numbers. But Python's pickle and Ruby's Marshal can pack instructions inside that box: "when opened, run this command." You unpack the box, and suddenly your system executes the attacker's code.
Python: pickle and PyYAML
pickle is Python's native serialization format. It can reconstruct arbitrary Python objects, including classes and functions. Attackers exploit __reduce__ methods or other magic methods that execute during unpickling:
# VULNERABLE: Never unpickle untrusted data
import pickle
user_data = pickle.loads(untrusted_input) # Can execute arbitrary code!
PyYAML with full loaders (yaml.load() without Loader=yaml.SafeLoader) can instantiate arbitrary Python objects, leading to code execution through specially crafted YAML.
Ruby: Marshal
Ruby's Marshal similarly preserves object state and can trigger code execution through deserialization callbacks and object initialization routines.
Why Dynamic Languages Are Vulnerable
Unlike Java or .NET (where gadget chains are needed), Python and Ruby's dynamic nature makes exploitation more straightforward—their serialization formats are designed for flexibility, not security boundaries.
Key Takeaway: Never deserialize untrusted data with pickle, Marshal, or unsafe YAML loaders. Use safer formats like JSON, or apply strict allowlists and cryptographic signatures if serialization of complex objects is unavoidable.