Programming Search⌘K

Weaknesscore

Deserialization of untrusted data

Also called insecure deserialization, unsafe deserialization, object injection, unmarshalling, unpickling, cwe-502.

Deserialization of untrusted data happens when a program rebuilds objects from bytes that an attacker controls, in a format that lets the bytes choose the classes to create or the code to run.

Abstraction
base
OWASP Top 10 (2025)
A08
CWE Top 25 (2025)
rank 15
Languages affected
java, python, csharp, php, ruby, javascript

Description

Serialization turns objects into bytes, so that a program can store them or send them. Deserialization reads the bytes and rebuilds the objects.1 A pure data format such as JSON rebuilds only numbers, strings, lists and maps. A native object format, such as pickle in Python, java.io serialization in Java or BinaryFormatter in .NET, rebuilds objects of any class that the bytes name. Some formats also run code of those classes while they rebuild, such as readObject in Java or a call that pickle records in the stream.45

The root cause is that the bytes decide what the program does. A developer thinks of the bytes as data: "this cookie holds the settings that the server wrote". The deserializer treats them as instructions: "import this class, call this function with these arguments". When an attacker can change the bytes, the attacker chooses the instructions. The Python documentation says that by default, unpickling will import any class or function that it finds in the data.5 Microsoft compares a call to BinaryFormatter.Deserialize with launching the payload as a standalone executable.8

The weakness is common because the native format is the shortest path. One call saves a whole object graph, and one call loads it back. The danger is not in the code of the program. It is in every class that the program can load, including the classes of its libraries. CWE-502 calls a sequence of instances and method calls that run during deserialization a gadget. It warns that more gadgets are found all the time, so an allowlist of classes alone is not sufficient.1 A type check after the load comes too late, because the code of the classes has already run.

The consequences vary with the classes that the program can load. CWE-502 lists changed data and unexpected state, denial of service, and in many cases the execution of code.1 CWE-502 is a base weakness, a child of CWE-913, improper control of dynamically-managed code resources. CWE-915, the uncontrolled change of object attributes, is its peer.1 It is rank 15 in the 2025 CWE Top 25, with 11 CVEs in the CISA catalogue of known exploited vulnerabilities, up from rank 16 the year before.2 The OWASP Top 10:2025 maps it to A08:2025 Software or Data Integrity Failures.3

History

On November 18, 2015, CVE-2015-4852 recorded that a crafted serialized Java object sent to Oracle WebLogic Server let remote attackers run commands. The record names a copy of the Apache Commons Collections library in the server.15 The named file is a library. A native deserializer can load any class on the class path, so the bytes can reach the code of every library, not only the code of the server.1 In 2016, Roger Riggs wrote JEP 290, "Filter Incoming Serialization Data". It added a filter interface to ObjectInputStream. The JDK calls the filter with the class of each object in the stream before it creates the object, and the filter accepts or rejects the class.6

Vulnerable code

A server keeps the settings of a user in a cookie. It writes the cookie with pickle and reads it back with pickle.loads. The second cookie is the classic demonstration input: the hand-made stream from the pickle documentation, with the harmless function print in place of the shell command of the documentation.5

This code runs but gives a wrong answer on purpose.

import base64
import pickle


def load_settings(cookie: str) -> dict:
    return pickle.loads(base64.b64decode(cookie))


cookie = base64.b64encode(pickle.dumps({"theme": "dark"})).decode()
print(load_settings(cookie))

# The demonstration stream from the pickle documentation, with print.
crafted = b"cbuiltins\nprint\n(S'code ran during loading'\ntR."
print(load_settings(base64.b64encode(crafted).decode()))
Output
{'theme': 'dark'}
code ran during loading
None

The program exits normally, and the output is the problem. The stream does not hold settings. It tells the unpickler to import builtins.print and to call it with a string. The call runs inside pickle.loads, before load_settings returns. Any function that the process can import could be in its place. The page does not show one.

Fixed code

The fix uses a pure data format and builds the result from the fields that the program expects. The OWASP cheat sheet says that a switch to a pure data format such as JSON is a large reduction of risk.4 CWE-502 asks to populate a fresh object, so that the data flows through input validation.1

import base64
import json

THEMES = {"dark", "light"}


def load_settings(cookie: str) -> dict:
    data = json.loads(base64.b64decode(cookie))
    if not isinstance(data, dict) or set(data) != {"theme"}:
        raise ValueError("unexpected fields")
    if data["theme"] not in THEMES:
        raise ValueError("unknown theme")
    return {"theme": data["theme"]}


cookie = base64.b64encode(json.dumps({"theme": "dark"}).encode()).decode()
print(load_settings(cookie))

crafted = b"cbuiltins\nprint\n(S'code ran during loading'\ntR."
try:
    load_settings(base64.b64encode(crafted).decode())
except ValueError as e:
    print("refused:", type(e).__name__)
Output
{'theme': 'dark'}
refused: JSONDecodeError

json.loads cannot import or call anything, so the crafted stream is only a syntax error. The program then accepts exactly one field with one of two values. The validation is part of the fix. A pure data format stops the code from running, but the values can still be wrong.4

When the format must stay

Some programs cannot change the format at once. Two controls then reduce the risk, and neither one makes untrusted bytes safe.

The first control is to accept only data that the program wrote itself. CWE-502 and OWASP both recommend a signature or an HMAC over the bytes, checked before the bytes go to the deserializer.13 An attacker without the key cannot make a valid tag. The pickle documentation suggests the same, with hmac.5 The Python example file shows it.

The second control is an allowlist of classes, checked before each object is created. In Python, a subclass of Unpickler overrides find_class and refuses every global that is not on the list.5 In Java, an ObjectInputFilter does the same. The pattern below allows one class and rejects all others with !*.7

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputFilter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

public class Main {
    record Settings(String theme) implements Serializable {}

    static byte[] save(Object value) throws IOException {
        var bytes = new ByteArrayOutputStream();
        try (var out = new ObjectOutputStream(bytes)) {
            out.writeObject(value);
        }
        return bytes.toByteArray();
    }

    static Object load(byte[] data) throws IOException, ClassNotFoundException {
        try (var in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            in.setObjectInputFilter(ObjectInputFilter.Config.createFilter("Main$Settings;!*"));
            return in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(load(save(new Settings("dark"))));
        try {
            load(save(new ArrayList<String>()));
        } catch (InvalidClassException e) {
            System.out.println("refused: " + e.getMessage());
        }
    }
}
Output
Settings[theme=dark]
refused: filter status: REJECTED

The filter runs before the object is created, so the code of a rejected class never runs.6 CWE-502 still calls an allowlist alone not sufficient, because a class on the list can itself be a gadget.1

How to detect it

  • Static analysis. CWE-502 rates automated static analysis as highly effective.1 CodeQL queries py/unsafe-deserialization, java/unsafe-deserialization and js/unsafe-deserialization follow data from a request to a deserializer.121314
  • Code review. Search for pickle.load, pickle.loads, ObjectInputStream.readObject, BinaryFormatter, and YAML loaders that are not the safe loader.4 For each call, find where the bytes come from. A file, a cookie, a cache, a queue and a model file are all inputs if another party can write them.
  • Traffic review. The OWASP cheat sheet lists signs of native formats in traffic. Base64 data that starts with rO0 is a Java object stream, and data that starts with gASV is often a pickle.43
  • Dependency review. List the libraries on the class path or in the environment. Each library adds classes that a native deserializer can load.1

How to prevent it

  • Do not deserialize untrusted data with a native object format. The pickle documentation says to unpickle only data that you trust.5 Microsoft says that BinaryFormatter is insecure and cannot be made secure.8
  • Use a pure data format and map it to declared types. Parse JSON into a data-transfer object that has only the fields the operation needs, then validate each field.41 In .NET, System.Text.Json creates a derived type only when the code declares it with a type discriminator.9 In Go, Decoder.DisallowUnknownFields makes the decoder refuse keys that the struct does not have.10
  • Sign the data that you write, and verify before you read. An HMAC or a digital signature shows that the bytes came from the expected source and were not changed.13
  • Allowlist the classes. Use ObjectInputFilter in Java and find_class in Python, and reject everything else.75 Keep the list short, and treat it as defence in depth.1
  • Watch for attribute injection. A merge of parsed data into an object can still change fields that the program did not expect. CWE-915 and, in JavaScript, CWE-1321 describe this, and the example files show it.1811

Real cases

Case Date What happened
CVE-2015-4852 published 2015-11-18 The WLS Security component of Oracle WebLogic Server let remote attackers run commands with a crafted serialized Java object in T3 protocol traffic. The record names a copy of Apache Commons Collections in the server.151
CVE-2017-9805 published 2017-09-15 The REST plugin of Apache Struts deserialized XML with XStream and no type filtering, which could lead to remote code execution.16
CVE-2024-37052 published 2024-06-04 MLflow deserialized untrusted data, so a scikit-learn model that an attacker uploaded could run code on the system of a user who interacted with it.171
PythonGitHub
import hashlib
import hmac
import pickle
import secrets

KEY = secrets.token_bytes(32)  # known only to the server


def save(value) -> bytes:
    data = pickle.dumps(value)
    tag = hmac.new(KEY, data, hashlib.sha256).digest()
    return tag + data


def load(blob: bytes):
    tag, data = blob[:32], blob[32:]
    expected = hmac.new(KEY, data, hashlib.sha256).digest()
    if not hmac.compare_digest(tag, expected):
        raise ValueError("bad signature")
    return pickle.loads(data)  # only bytes that this server wrote


print(load(save({"theme": "dark"})))

crafted = b"cbuiltins\nprint\n(S'code ran during loading'\ntR."
try:
    load(bytes(32) + crafted)
except ValueError as e:
    print("refused:", e)
Output
{'theme': 'dark'}
refused: bad signature

The server signs each stream that it writes and checks the tag before pickle.loads. A stream that the server did not write has no valid tag, so it never reaches the unpickler. hmac.compare_digest compares in constant time. The control fails if the key leaks, and it does not help when another party is allowed to write the data.

import builtins
import io
import pickle

SAFE_BUILTINS = {"range", "complex", "set", "frozenset", "slice"}


class RestrictedUnpickler(pickle.Unpickler):
    def find_class(self, module, name):
        if module == "builtins" and name in SAFE_BUILTINS:
            return getattr(builtins, name)
        raise pickle.UnpicklingError(f"global '{module}.{name}' is forbidden")


def restricted_loads(data: bytes):
    return RestrictedUnpickler(io.BytesIO(data)).load()


print(restricted_loads(pickle.dumps([1, 2, range(3)])))

crafted = b"cbuiltins\nprint\n(S'code ran during loading'\ntR."
try:
    restricted_loads(crafted)
except pickle.UnpicklingError as e:
    print("refused:", e)
Output
[1, 2, range(0, 3)]
refused: global 'builtins.print' is forbidden

The pickle documentation gives this allowlist. find_class runs for every class and every function that the stream asks for, so it can refuse print before the call.

  • Verdict: stdlib. pickle and shelve run code from the data. json builds only dictionaries, lists, strings, numbers, booleans and None.
  • Use json and validate the fields for any data from outside the process.
  • Use an HMAC when the program must read back its own pickles from a place that others can reach.
  • find_class is an allowlist, not a sandbox. Keep the list to plain data types.
JavaGitHub

This code runs but gives a wrong answer on purpose.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {
    record Settings(String theme) implements Serializable {}

    // A class that the program can load, with code that runs on load.
    static class Audit implements Serializable {
        private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
            in.defaultReadObject();
            System.out.println("Audit.readObject ran");
        }
    }

    static byte[] save(Object value) throws IOException {
        var bytes = new ByteArrayOutputStream();
        try (var out = new ObjectOutputStream(bytes)) {
            out.writeObject(value);
        }
        return bytes.toByteArray();
    }

    static Settings load(byte[] data) throws IOException, ClassNotFoundException {
        try (var in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            return (Settings) in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(load(save(new Settings("dark"))));
        try {
            load(save(new Audit()));
        } catch (ClassCastException e) {
            System.out.println("ClassCastException, after the object was built");
        }
    }
}
Output
Settings[theme=dark]
Audit.readObject ran
ClassCastException, after the object was built

The cast to Settings looks like a type check. readObject builds the object first, and the code of its class runs during the build. The cast fails after that code has run.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputFilter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {
    record Settings(String theme) implements Serializable {}

    static class Audit implements Serializable {
        private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
            in.defaultReadObject();
            System.out.println("Audit.readObject ran");
        }
    }

    static byte[] save(Object value) throws IOException {
        var bytes = new ByteArrayOutputStream();
        try (var out = new ObjectOutputStream(bytes)) {
            out.writeObject(value);
        }
        return bytes.toByteArray();
    }

    static Settings load(byte[] data) throws IOException, ClassNotFoundException {
        try (var in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            in.setObjectInputFilter(ObjectInputFilter.Config.createFilter("Main$Settings;!*"));
            return (Settings) in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(load(save(new Settings("dark"))));
        try {
            load(save(new Audit()));
        } catch (InvalidClassException e) {
            System.out.println("refused: " + e.getMessage());
        }
    }
}
Output
Settings[theme=dark]
refused: filter status: REJECTED

The filter sees the class Main$Audit before the object exists and rejects it, so Audit.readObject does not run.

  • Verdict: stdlib. java.io serialization can create any serializable class on the class path. ObjectInputFilter filters classes, array sizes and the depth of the stream.
  • Prefer a pure data format, and parse it into records that hold only the needed fields.
  • If a program must read Java object streams, set a filter on each stream or a JVM-wide filter with jdk.serialFilter, and end the pattern with !*.
  • The OWASP cheat sheet shows a final readObject that always throws, for a class that must never be deserialized.

This code runs but gives a wrong answer on purpose.

using System.Text.Json;
using System.Text.Json.Serialization;

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    TypeInfoResolver = AccountJson.Default,
};
string body = """{"name": "mallory", "theme": "dark", "isAdmin": true}""";

// The request body binds straight to the stored account.
Account account = JsonSerializer.Deserialize<Account>(body, options)!;
Console.WriteLine($"{account.Name}: theme {account.Theme}, admin {account.IsAdmin}");

class Account
{
    public string Name { get; set; } = "";
    public string Theme { get; set; } = "light";
    public bool IsAdmin { get; set; }
}

[JsonSerializable(typeof(Account))]
partial class AccountJson : JsonSerializerContext;
Output
mallory: theme dark, admin True

System.Text.Json creates only the type that the code names, so the bytes cannot choose a class. The risk moves to the fields. The request sets IsAdmin, because the stored type has that property. This is CWE-915, the peer of CWE-502.

using System.Text.Json;
using System.Text.Json.Serialization;

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
    TypeInfoResolver = RequestJson.Default,
};

foreach (string body in new[]
{
    """{"theme": "dark"}""",
    """{"theme": "dark", "isAdmin": true}""",
})
{
    try
    {
        SettingsRequest request = JsonSerializer.Deserialize<SettingsRequest>(body, options)!;
        Console.WriteLine($"theme {request.Theme}");
    }
    catch (JsonException)
    {
        Console.WriteLine("refused: unexpected field");
    }
}

// Only the fields that this operation may change.
record SettingsRequest(string Theme);

[JsonSerializable(typeof(SettingsRequest))]
partial class RequestJson : JsonSerializerContext;
Output
theme dark
refused: unexpected field

The request type has only the field that the operation may change, and the options refuse a key that the type does not have.

  • Verdict: stdlib. Microsoft says that BinaryFormatter is insecure and cannot be made secure, and its in-box implementation throws exceptions on use. System.Text.Json builds only declared types, and a derived type needs a declared type discriminator.
  • Deserialize into request types that hold only the fields that the operation needs.
  • Do not use BinaryFormatter, SoapFormatter, NetDataContractSerializer, LosFormatter or ObjectStateFormatter on data from outside the process.
JavaScriptGitHub

This code runs but gives a wrong answer on purpose.

function merge(target, source) {
  for (const key of Object.keys(source)) {
    const value = source[key];
    if (value !== null && typeof value === "object") {
      if (typeof target[key] !== "object" || target[key] === null) {
        target[key] = {};
      }
      merge(target[key], value);
    } else {
      target[key] = value;
    }
  }
  return target;
}

const settings = merge({}, JSON.parse('{"theme": "dark"}'));
console.log("theme:", settings.theme);

// The classic demonstration input for prototype pollution.
merge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));
const user = {};
console.log("an empty object, isAdmin:", user.isAdmin);
Output
theme: dark
an empty object, isAdmin: true

JSON.parse is safe on its own: it makes __proto__ an ordinary key of the parsed object. The merge then reads target["__proto__"], which is Object.prototype, and writes isAdmin into it. Every object in the program now inherits isAdmin. CWE-1321 describes the same pattern with the path __proto__.isAdmin.

const FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);

function merge(target, source) {
  for (const key of Object.keys(source)) {
    if (FORBIDDEN.has(key)) {
      throw new Error(`refused key: ${key}`);
    }
    const value = source[key];
    if (value !== null && typeof value === "object") {
      if (!Object.hasOwn(target, key) || typeof target[key] !== "object" || target[key] === null) {
        target[key] = Object.create(null);
      }
      merge(target[key], value);
    } else {
      target[key] = value;
    }
  }
  return target;
}

const settings = merge(Object.create(null), JSON.parse('{"theme": "dark"}'));
console.log("theme:", settings.theme);

try {
  merge(Object.create(null), JSON.parse('{"__proto__": {"isAdmin": true}}'));
} catch (e) {
  console.log(e.message);
}
const user = {};
console.log("an empty object, isAdmin:", user.isAdmin);
Output
theme: dark
refused key: __proto__
an empty object, isAdmin: undefined

The merge refuses the three keys that reach a prototype, as CWE-1321 recommends, and it reads only own properties of the target. Objects from Object.create(null) have no prototype at all.

  • Verdict: native. JSON.parse builds only plain objects, arrays, strings, numbers, booleans and null, and it does not call code. Do not use eval or the Function constructor to parse data.
  • Copy the expected fields into a fresh object instead of a deep merge of the whole input.
  • Use a Map for keys that come from input.
  • The reviver argument of JSON.parse runs for each value. Keep it free of lookups that create objects from names in the data.

This code runs but gives a wrong answer on purpose.

package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

type Account struct {
	Name    string `json:"name"`
	Theme   string `json:"theme"`
	IsAdmin bool   `json:"isAdmin"`
}

func main() {
	body := `{"name": "mallory", "theme": "dark", "isAdmin": true}`
	var account Account
	if err := json.NewDecoder(strings.NewReader(body)).Decode(&account); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("%s: theme %s, admin %t\n", account.Name, account.Theme, account.IsAdmin)
}
Output
mallory: theme dark, admin true

encoding/json fills only the type that the code passes, so the bytes cannot choose a type. The request still sets IsAdmin, because the stored type has that field.

package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
)

// Only the fields that this operation may change.
type SettingsRequest struct {
	Theme string `json:"theme"`
}

func parse(body string) (SettingsRequest, error) {
	var request SettingsRequest
	decoder := json.NewDecoder(strings.NewReader(body))
	decoder.DisallowUnknownFields()
	if err := decoder.Decode(&request); err != nil {
		return SettingsRequest{}, err
	}
	if request.Theme != "dark" && request.Theme != "light" {
		return SettingsRequest{}, errors.New("unknown theme")
	}
	return request, nil
}

func main() {
	for _, body := range []string{`{"theme": "dark"}`, `{"theme": "dark", "isAdmin": true}`} {
		request, err := parse(body)
		if err != nil {
			fmt.Println("refused:", err)
			continue
		}
		fmt.Println("theme", request.Theme)
	}
}
Output
theme dark
refused: json: unknown field "isAdmin"

DisallowUnknownFields makes the decoder return an error for a key that matches no field of the struct.

  • Verdict: stdlib. encoding/json, encoding/xml and encoding/gob decode into types that the program passes. The bytes do not name a class to create.
  • Decode into a request type with only the needed fields, call DisallowUnknownFields, and validate the values.
  • Decoding into any gives maps and slices, not program types. Check each value before use.

References

  1. CWE-502: Deserialization of Untrusted Data, Description; Alternate Terms; Common Consequences; Potential Mitigations; Background Details; Relationships; Detection Methods; Observed Examples
  2. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 15, CVEs in KEV, Rank Last Year
  3. OWASP Top 10:2025, A08:2025 Software or Data Integrity Failures, Description; How to prevent; Scenario
  4. OWASP Cheat Sheet Series, Deserialization Cheat Sheet, What is Deserialization; Python, Clear-box Review; Java, Harden Your Own java.io.ObjectInputStream; Language-Agnostic Methods for Deserializing Safely
  5. The Python Standard Library, pickle, the warning at the top; Restricting Globals; Unpickler.find_class
  6. JEP 290: Filter Incoming Serialization Data, Summary; Motivation; Description
  7. Java SE 25 API, java.io.ObjectInputFilter, the interface description, the filter pattern example
  8. .NET documentation, Deserialization risks in use of BinaryFormatter and related types, the caution at the top; Deserialization vulnerabilities; BinaryFormatter security vulnerabilities
  9. .NET documentation, How to serialize properties of derived classes with System.Text.Json, Polymorphic type discriminators
  10. Go standard library, encoding/json, Decoder.DisallowUnknownFields
  11. CWE-1321: Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution'), Description; Demonstrative Examples, Example 1
  12. CodeQL query help, Deserialization of user-controlled data (py/unsafe-deserialization), the query description; Recommendation
  13. CodeQL query help, Deserialization of user-controlled data (java/unsafe-deserialization), the query description; Recommendation
  14. CodeQL query help, Deserialization of user-controlled data (js/unsafe-deserialization), the query description
  15. CVE-2015-4852, Oracle WebLogic Server, the description and the publication date
  16. CVE-2017-9805, Apache Struts REST plugin, the description and the publication date
  17. CVE-2024-37052, MLflow, the description and the publication date
  18. CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes, Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/YVTK68/text.yaml