Deserialisation and eval: when data becomes code
Some formats describe how to rebuild objects, and rebuilding an object can run code.
Remember: Use data-only formats such as JSON, validate their shape, and never let the client choose the class to instantiate.
Deserialisation turns bytes back into objects. Formats such as Python pickle, Java serialisation, PHP serialize and some YAML loaders can instantiate arbitrary classes or call their constructors. Reading untrusted input with them is code execution, often before any authentication has run.
- Python: pickle, marshal, yaml.load without SafeLoader, and shelve on untrusted data.
- PHP: unserialize() on user data. Magic methods such as __wakeup and __destruct can run during object injection.
- Java and Kotlin: ObjectInputStream.readObject on untrusted streams, and JSON libraries with polymorphic typing enabled.
- JavaScript: eval, new Function, vm running user strings, and serialisation libraries that evaluate functions.
- Templates: a template engine that compiles user-supplied templates runs code on the server.
config = yaml.load(request.data)
config = yaml.safe_load(request.data)
settings = Settings.model_validate(config) # then check the shape
What to do
- Use data-only formats (JSON) and validate their shape with a schema.
- If a rich format is unavoidable, sign it and verify the signature before the parser runs.
- Never let a client choose the class to instantiate.
- Search the codebase for the sinks: pickle.loads, yaml.load, unserialize, readObject, eval.
A cookie, a hidden form field or a message from a queue is untrusted input. A signed value is only as safe as the secret key and the order of operations: verify the signature first, then parse.
Questions to ask yourself
- Does this format describe data, or describe how to build objects?
- Who controls the bytes that are being loaded?
- Is the signature verified before the parser runs?
Practise this
- Preferences stored as a pickle in a cookie · Injection & input
- Session read with Java serialisation · Injection & input