KHAGAN AYDIN

OWASP 2017 A8: Insecure Deserialization

When you rebuild an object from bytes, the sender picks which code runs.

· 11 min read

Insecure Deserialization is a security vulnerability in which an application rebuilds an object from data an attacker controls, and the attacker uses that rebuilding step to run code on the server. It is number eight on the OWASP Top 10 2017. It is new: not on the 2013 list in any form, and one of three entries added in 2017, alongside XML External Entities and Insufficient Logging and Monitoring. It got in a different way. Most items earned their place from scan and breach data; this one came from a survey of practitioners, who had watched deserialization bugs turn into full server takeover between 2015 and 2017 and wanted it named.

Here is the plain version. Serialization turns a live object in memory into a flat string of bytes you can store or send. Deserialization is the reverse. The danger is that rebuilding an object is not a passive copy: the language runs code to do it, and an attacker who controls the bytes can steer that code.

What serialization is, and why rebuilding is dangerous

Every language can flatten an object. Java has ObjectOutputStream, .NET has BinaryFormatter, PHP has serialize(), Python has pickle, Ruby has Marshal. They all take a structure in memory, with its fields and its type, and produce bytes you can write to a cookie, a cache, a queue or a file, then turn back later.

The trap is in those last three words. These formats carry the object’s class, and on the way back in, the runtime creates an object of that class and fills it. To do that it calls methods: a constructor, a setter, a callback the class defines for exactly this moment, or a cleanup method that runs when the object is destroyed. If the attacker chooses the class and the field values, the attacker chooses which of those methods runs and with what inputs. The real question is never whether your parser is safe. It is whether you let a stranger pick which objects your program builds. If the bytes came from a cookie, request body or queue, the answer is yes.

Gadget chains, in plain words

The obvious worry is an attacker sending an object of some dangerous class of their own. That is not how the serious attacks work, because the dangerous class is usually not on the server. The real technique uses classes that are already there.

A gadget is an ordinary class, already loaded in your application or a library, that does something useful to an attacker when one of its automatic methods runs: it reads a file, opens a connection, or calls a method named in one of its fields. On its own a gadget is harmless. A gadget chain links several: the first gadget’s cleanup method calls into a second, whose field points at a third, until the last runs a system command. The attacker serializes this nest and sends it, and your runtime walks the chain and executes it, without ever running a line of the attacker’s code.

The classic example is a library almost nobody imported on purpose: Apache Commons Collections, a Java toolkit pulled in as a dependency of a dependency. It contains a class that calls a named method on an object by reflection. Chained with a couple of its neighbors, it turns “deserialize these bytes” into “run this command.” In November 2015 the security firm FoxGlove Security showed this chain giving remote code execution on WebLogic, WebSphere, JBoss, Jenkins and OpenNMS, five widely deployed Java products, using a payload generator built from a January 2015 conference talk. The class had shipped for years. Nobody treated accepting serialized objects as the bug, because the bug was not in any single class. It was in deserializing.

It is not only Java

.NET. BinaryFormatter, SoapFormatter and NetDataContractSerializer all reconstruct arbitrary types and run code along the way. Microsoft’s own documentation warns against using BinaryFormatter on untrusted input. JSON is not automatically safe either. At the Black Hat conference in 2017, researchers showed that libraries which record each value’s type, Json.NET with TypeNameHandling turned up or Jackson with default typing on, reopen the same door: the type tag names the class to build.

PHP. unserialize() on a user-controlled string lets the attacker instantiate any loaded class with fields of their choosing. If such a class does something sensitive in its __wakeup() or __destruct() method, that runs. This is PHP object injection, behind the critical Joomla flaw of December 2015 (CVE-2015-8562): a crafted User-Agent header was stored in the session and deserialized into code execution, exploited in the wild for two days before a patch existed.

Python. pickle.loads() on untrusted bytes is remote code execution by design: the format includes an opcode that calls a function the attacker names with the arguments they supply. The documentation says plainly never to unpickle data from an untrusted source. The same covers yaml.load() from older PyYAML, the Python library for the YAML data format, without a safe loader.

Ruby. Marshal.load() and unsafe YAML.load rebuild arbitrary objects. The Rails flaw CVE-2013-0156, from January 2013, is the landmark: the XML parameter parser could be steered into decoding a value as YAML, which instantiated objects and reached code execution on, as the advisory put it, all versions at the time. Cookie sessions in Rails before 4.1 used Marshal, so an attacker who learned the secret key could forge a cookie carrying a gadget chain.

The pattern throughout: one call rebuilds an object from bytes, and the source is something a user controls.

Vulnerable and fixed: Java

A shopping cart kept in a cookie, read on every request:

Vulnerable code

import java.io.*;
import java.util.Base64;

public class CartCookie {
    public static Cart read(String cookieValue) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(cookieValue);
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
        return (Cart) in.readObject();   // runs before the cast to Cart
    }
}

The cast to Cart is the false comfort. readObject() builds whatever class the bytes name and runs its chain first; the ClassCastException arrives after the command has run. A serialized HashMap sent to this method throws the cast error only after the object is fully rebuilt, by which point any gadget chain has already executed.

The right fix is to stop putting objects in the cookie: send plain data with a schema and rebuild it under your own rules.

Fixed code

import com.fasterxml.jackson.databind.ObjectMapper;

public class CartJson {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    // Never call MAPPER.activateDefaultTyping(...). Default typing reopens the hole.

    public static Cart read(String json) throws Exception {
        Cart cart = MAPPER.readValue(json, Cart.class);
        if (cart.items == null || cart.items.length > 50) {
            throw new IllegalArgumentException("invalid cart");
        }
        for (Item item : cart.items) {
            if (item.sku == null || !item.sku.matches("[A-Z0-9]{4,20}")
                    || item.qty < 1 || item.qty > 99) {
                throw new IllegalArgumentException("invalid item");
            }
        }
        return cart;
    }
}

Jackson, with default typing off, binds the JSON only into the Cart and Item fields you declared. It will not build a class the document names, and an unknown field is rejected. A valid cart is read; an out-of-range quantity and an unknown field are both refused.

When you cannot avoid native Java serialization, for example an old internal protocol, add an allow list. Write one by extending ObjectInputStream and overriding resolveClass to reject any class not on a fixed set. Override resolveProxyClass too, to throw on every proxy: without that, an attacker smuggles a gadget in behind a dynamic proxy and a class-name allow list never sees it, the detail most examples miss.

Better, use the built-in version. The January 2017 Java updates (8u121, 7u131 and 6u141) added JEP 290 (a JEP is a JDK Enhancement Proposal), a process-wide filter set with a system property:

-Djdk.serialFilter=com.example.cart.*;java.util.ArrayList;maxdepth=5;maxbytes=16384;!*

Read right to left, !* rejects everything not already allowed. Both approaches stop the attack: a hand-written resolveClass allow list throws InvalidClassException on a HashMap, and the JEP 290 filter rejects a HashMap while allowing the cart. The maxbytes and maxdepth limits also blunt denial-of-service payloads (a deeply nested structure that explodes on rebuild) that an allow list alone ignores.

Vulnerable and fixed: PHP

Vulnerable code

<?php
class TempFile {
    public $path;
    public function __destruct() {
        if ($this->path && file_exists($this->path)) {
            unlink($this->path);   // deletes whatever path the object carries
        }
    }
}

// Remembers the user's list settings between visits.
$prefs = unserialize(base64_decode($_COOKIE['prefs']));

Nothing here means to touch user files. But unserialize() will build a TempFile whose path is /var/www/app/config/database.php, and when that object is destroyed at the end of the request, PHP calls __destruct() and deletes it. The application has handed an attacker a file-deletion tool, and with a richer gadget, code execution. Given a serialized TempFile, the vulnerable version deletes whatever file the object names.

Fixed code

<?php
function read_prefs($cookie) {
    $data = json_decode(base64_decode($cookie, true), true);
    if (!is_array($data)) {
        return array('sort' => 'date', 'per_page' => 20);
    }
    $sort = isset($data['sort']) && in_array($data['sort'], array('date', 'name', 'price'), true)
        ? $data['sort'] : 'date';
    $perPage = isset($data['per_page']) ? (int) $data['per_page'] : 20;
    return array('sort' => $sort, 'per_page' => max(10, min($perPage, 100)));
}

$prefs = read_prefs(isset($_COOKIE['prefs']) ? $_COOKIE['prefs'] : '');

JSON carries data, not classes, so decoding it can never build a TempFile, and the settings are forced into a known shape. If you are stuck with unserialize() on PHP 7, pass array('allowed_classes' => false) as the second argument: any object becomes a harmless __PHP_Incomplete_Class whose methods never run. That turns the TempFile payload into a stub with no destructor to fire. It is a brake, not the real fix, which is to stop deserializing untrusted input into objects.

Why signing and encryption only half help

A common response is to sign the serialized blob so the server rejects anything it did not produce. Done exactly right, signing closes the attack, because an attacker can no longer supply bytes that pass the check. The fixed Python example below does this.

It fails in the ways real systems fail. If the signing key leaks (committed to a repository, shared across environments, or left at a default), the attacker signs their own gadget chain and you are back to full compromise; that is how forged Rails session cookies worked. If you verify the signature after deserializing instead of before, the check is theatre: the object is already built. Signing protects the channel. It does not make deserializing objects safe.

The fix that actually ends it

Do not deserialize untrusted data into live objects. Move it across your trust boundary in a format that carries only data, never types: JSON, or a schema format such as Protocol Buffers. Rebuild your objects from that data with explicit validation, as the fixed examples do. A data format cannot name a class, so there is no gadget to reach.

Then layer the rest for places you cannot convert at once:

  • Turn on the language’s filter or allow list (JEP 290 in Java, allowed_classes in PHP, safe_load in PyYAML, the :json cookie serializer in Rails).
  • Sign data correctly: authenticate before you deserialize, with a per-environment key kept out of source control.
  • Run any component that must deserialize untrusted input under a low-privilege account that cannot reach your internal network.
  • Log and alert on deserialization failures. A burst of them is someone probing gadget chains.

Here is the signed, data-only version in Python, replacing pickle. The cookie is payload.mac, where payload is base64 JSON and mac is its HMAC, a keyed signature that proves the server wrote the payload. The ordering is the whole trick:

def load_layout(cookie):
    payload, _, mac = cookie.partition(".")
    if not hmac.compare_digest(sign(payload.encode()), mac):   # verify BEFORE decoding
        abort(400)
    layout = json.loads(base64.urlsafe_b64decode(payload).decode())
    widgets = layout.get("widgets") if isinstance(layout, dict) else None
    if not isinstance(widgets, list) or len(widgets) > 12 \
            or not all(w in ALLOWED_WIDGETS for w in widgets):
        abort(400)
    return {"widgets": widgets}

A valid cookie returns 200, while a tampered signature, a disallowed widget and plain garbage each return 400. Even with the signature check removed, json.loads cannot build an object, so the worst case is bad data, not code execution. That is the point of a data format: it fails safe.

How to spot serialized data in traffic

Serialized blobs hide in cookies, hidden fields, headers, API bodies and queues. Learn the signatures:

Format Base64 starts with Raw bytes (hex)
Java rO0AB AC ED 00 05
.NET BinaryFormatter AAEAAAD///// 00 01 00 00 00 FF FF FF FF
PHP serialize Tzo (for O:), YToy (for a:2) 4F 3A (O:), 61 3A (a:)
Python pickle gAJ, gAN, gAS (protocols 2 to 4) 80 02 to 80 04
Ruby Marshal BAh 04 08

Generate one in each language and the prefix is unmistakable. In Burp Suite, decode every cookie and parameter and watch for them. A response Content-Type of application/x-java-serialized-object is a flashing sign that native serialization crosses the network.

How to test your own application

  1. Grep for the sinks: readObject, BinaryFormatter, unserialize, pickle.loads, yaml.load, Marshal.load. Trace each input back; if it can reach a request, cookie, header, queue or attacker-influenced file, it is a finding.
  2. Decode cookies and tokens. If any is a serialized object (check the table), that feature is probably built on deserializing untrusted input.
  3. Run a software composition scan. Gadget chains live in libraries, so your dependency versions tell you which chains you carry.
  4. For a safe probe, send valid serialized data that references a class which does not exist. A deserialization error, not a validation error, means the input is deserialized before it is checked.

Checklist

  • No readObject, BinaryFormatter, unserialize, pickle.loads, Marshal.load or unsafe yaml.load on data a user influences.
  • Cross-boundary data moves as JSON or a schema format, rebuilt with explicit validation.
  • Where native deserialization remains, an allow list that also blocks proxies, plus depth and size limits (JEP 290 in Java).
  • Signatures verified before deserializing, with per-environment keys kept out of source control.
  • Deserializing components run with low privilege and limited network reach.
  • Deserialization failures logged and alerted on.

Insecure deserialization is new to the list only in that the list caught up. The bugs had landed for years, and they are among the worst you can ship: no memory corruption, no clever overflow, just a feature that trusts its input doing what it was built to do. The way out is not a cleverer filter. It is to stop turning strangers’ bytes into objects, and to move data as data.