EMZETT.
Login

Insecure deserialisation: when data becomes code

In short: When deserialising, stored bytes become objects again; if the input comes from attackers, some formats (pickle, Java serialisation, YAML) can execute arbitrary code.

In more detail: Serialising converts objects into bytes/text (storing, sending), deserialising back. Some formats may create objects of arbitrary classes and call methods: with untrusted data a gateway for remote code execution (RCE).

In Depth

Dangerous formats

  • Python pickle (and shelve, joblib/torch.load with pickle): can execute arbitrary code on load. Never load foreign pickle/model files! → safetensors, JSON.
  • Java ObjectInputStream (serialisation): famous gadget chains (Apache Commons Collections), source of many server vulnerabilities.
  • PHP unserialize(), Ruby Marshal, .NET BinaryFormatter (deprecated), YAML (yaml.load instead of safe_load), XML deserialisation/XXE, Node node-serialize.
  • Safer: JSON (pure data) with schema validation (Zod, pydantic), Protocol Buffers.

What an attack looks like (principle)

The attacker supplies a crafted object (cookie, session data, API body, uploaded file, cache entry, message queue). On loading, constructors/methods of the contained classes are called (e.g. __reduce__ with pickle) that execute commands. Consequences: server takeover, data exfiltration. Known cases: Java server flaws (e.g. in application servers), Ruby on Rails YAML 2013, numerous AI model files on Hugging Face with malicious code.

Defence

  • No deserialisation of untrusted data with powerful formats.
  • Data formats without code semantics (JSON) + validation; build objects yourself from validated fields.
  • Sign/encrypt serialised data (HMAC), verify integrity before deserialising; store session data server-side.
  • Allowlists for classes (Java ObjectInputFilter), keep libraries current.
  • ML models: safetensors/ONNX, check sources, weights_only=True in torch.load.
  • Sandbox/container, minimal rights, monitoring.
  • Scan dependencies (SCA), yaml.safe_load.

Checking and learning

  • Search code: pickle.loads, yaml.load, ObjectInputStream, unserialize, BinaryFormatter, eval.
  • OWASP Top 10: “Software and Data Integrity Failures”.
  • Practise legally: OWASP WebGoat/Juice Shop, TryHackMe rooms.
  • Rule of thumb: data are not programs: a format that mixes data and code is risky.
  • Related: injection, supply-chain attacks, HMAC, JSON validation (Zod), exchanging AI models (ONNX).

See also: OWASP Top 10, ONNX and model export