---
title: "Never rebuild objects from untrusted data · Agent Wranglers"
url: https://agentwranglers.se/playbook/adversarial-testing/injection/unsafe-deserialisation
updated: 2026-10-20
licence: "All rights reserved"
---

# Never rebuild objects from untrusted data

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Required
- Chapter: [Injection](https://agentwranglers.se/playbook/adversarial-testing/injection)
- Rule: Read untrusted data only as plain data, such as JSON. Never use formats that can rebuild code objects.
- How: Avoid Python `pickle`, Java serialisation, PHP `unserialize` and YAML loaders that create objects. Use the safe loader, such as `yaml.safe_load`. Sign any data you send out and read back, such as cookies.
- Check: Search the code for `pickle.loads`, `yaml.load(`, `unserialize(`, `ObjectInputStream` and `BinaryFormatter`. No match reads data from outside. Change one byte of every signed cookie and hidden field. The server rejects it with a 400 and never a 500.

Example:

```python
# Bad: pickle and the full YAML loader can run code
data = pickle.loads(cookie_bytes)
data = yaml.load(body, Loader=yaml.Loader)
# Good: plain data only
data = json.loads(body)
data = yaml.safe_load(body)
```

```php
// Bad: unserialize can build any object
$cart = unserialize($_COOKIE['cart']);
// Good: plain data only
$cart = json_decode($_COOKIE['cart'], true, 16, JSON_THROW_ON_ERROR);
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers security testing playbook: https://agentwranglers.se/playbook/adversarial-testing/injection/unsafe-deserialisation`.

- Previous: [Turn off external entities in XML](https://agentwranglers.se/playbook/adversarial-testing/injection/xml-entities)
- Next: [Block prototype pollution](https://agentwranglers.se/playbook/adversarial-testing/injection/prototype-pollution)
- [Injection](https://agentwranglers.se/playbook/adversarial-testing/injection)
