Join our Newsletter — 33% off our NHI Course
Home› Guides› Secure Deserialisation Guide: Avoiding Unsafe Object Loading
Guide Application Security

Secure Deserialisation Guide: Avoiding Unsafe Object Loading

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 26 October 2026 16 min read
On this page

Most deserialisation vulnerabilities are design decisions: somewhere in the code, the incoming bytes are allowed to choose which classes get built. This guide is for developers, architects and AppSec engineers who own serialisation code and want to build it safely rather than patch it after a finding. It covers how to design data contracts that cannot name types, how to configure the common loaders in Java, .NET, Python, PHP and Ruby so they fail closed, how to roll out Java serialisation filters without breaking production, and how to handle the signing keys that protect round-tripped state. The threat background, recognition markers and model-file risks are covered in the Insecure Deserialisation Guide; this page is the engineering companion.

Key takeaways

  • Take type authority away from the input. If the stream can name a class, a filter is the only thing between it and the gadget chains on your classpath. Bind untrusted data to fixed, declared types instead.
  • Configure loaders to fail closed. Several common libraries are safe only with a specific setting: SnakeYAML with SafeConstructor, Kryo with class registration on, PHP unserialize() with allowed_classes, Newtonsoft Json.NET with TypeNameHandling.None.
  • Some serialisers cannot be fixed. Microsoft states that BinaryFormatter is insecure and cannot be made secure, and the in-box implementation throws exceptions on use from .NET 9. Plan migrations, do not plan mitigations.
  • Signing proves origin, not safety. An HMAC or signature only helps while the key stays secret. Leaked ASP.NET machine keys and a forged licence signature in Fortra GoAnywhere both turned "trusted" serialised data into remote code execution.
  • Roll out filters in observe mode first. Java filters log rejections to the java.io.serialization logger; run with logging on, build the allowlist from real traffic, then enforce with a trailing !*.

Who chooses the type: the design decision behind every loader

Serialisation formats differ less in syntax than in who decides which class is instantiated. That single property predicts most of the risk. The OWASP Deserialization Cheat Sheet makes the same point in its advice to switch to pure data formats and a data-transfer object pattern, and CWE-502 lists "populate new objects" (build a fresh object from validated data instead of deserialising directly) as a mitigation.

Type authorityTypical examplesWhat an attacker controlsUse with untrusted input?
Fixed target type (data only)JsonSerializer.Deserialize<OrderDto>(), Jackson readValue(json, OrderDto.class), Protocol Buffers generated classes, Python json.loads() then a schemaField values onlyYes, with validation and size limits
Closed polymorphism (declared subtypes by logical name)System.Text.Json [JsonDerivedType], Jackson @JsonTypeInfo(use = Id.NAME) with @JsonSubTypesA choice among types the developer listedYes, if the list contains only plain data types
Open polymorphism (class name in the payload)Jackson default typing or Id.CLASS, Json.NET TypeNameHandling.Auto/All, fastjson autotype, XStream without an allowlistAny class on the classpath that the library will loadNo, unless a strict allowlist is enforced before instantiation
Native object graphsJava ObjectInputStream, .NET BinaryFormatter, Python pickle, PHP unserialize(), Ruby Marshal.loadClass choice plus the callbacks those classes run during reconstructionNo. Python, PHP and Ruby documentation all warn against loading untrusted data

The practical rule: every untrusted path should sit in the first two rows. Native formats and open polymorphism belong only between components that share one owner and one key, and even then the cost of a leaked key (see below) argues for data-only formats.

Configuring common loaders to fail closed

The table below gives the setting that makes each loader safe for untrusted data, taken from the vendors' own documentation and the OWASP cheat sheet. The Insecure Deserialisation Guide lists how to recognise each format in traffic; this table is about what to put in code and configuration.

Platform and loaderUnsafe usageFail-closed configuration
Java ObjectInputStreamAny readObject() on network, cookie or queue data with no filter (filtering is off by default)Replace with a data format; where that is not yet possible, set an ObjectInputFilter per stream or jdk.serialFilter with limits and a trailing !*
Jackson databindDefault typing, or @JsonTypeInfo(use = Id.CLASS) on fields of type ObjectNo polymorphism, or Id.NAME with @JsonSubTypes; if default typing is unavoidable, activateDefaultTyping() with a restrictive PolymorphicTypeValidator
SnakeYAMLDefault constructor on untrusted YAMLorg.yaml.snakeyaml.constructor.SafeConstructor
XStreamVersions before 1.4.17, or relaxed security framework1.4.17 or later with the default allowlist kept, adding only your own types
KryoClass registration turned offRegistration required (the default from v5.0.0)
fastjson / fastjson2fastjson below 1.2.68; autotype enabledfastjson 1.2.68+ with safemode on, or fastjson2 with autotype off
.NET BinaryFormatter, SoapFormatter, NetDataContractSerializer, LosFormatter, ObjectStateFormatterAny use; Microsoft says the four siblings perform unrestricted polymorphic deserialisation like BinaryFormatterMigrate to System.Text.Json, XmlSerializer or DataContractSerializer; a SerializationBinder is not a fix
Newtonsoft Json.NETTypeNameHandling other than NoneTypeNameHandling.None; if types must travel, a custom SerializationBinder allowlist
System.Text.Json (.NET 7+)Custom converters that call Type.GetType() on a payload valueBuilt-in polymorphism only accepts derived types declared with [JsonDerivedType]
Python pickle, jsonpicklepickle.loads() or jsonpickle.decode() on anything that could be tampered withjson plus schema validation; for legacy internal pickles, a RestrictedUnpickler overriding find_class()
PyYAMLyaml.load() with Loader=yaml.Loader or UnsafeLoader, yaml.unsafe_load()yaml.safe_load()
PHP unserialize()Default call, which accepts all classesjson_decode(); for internal data, ['allowed_classes' => false, 'max_depth' => 64]. The manual warns not to pass user input even with allowed_classes
Ruby Marshal.loadAny user-supplied or untrusted dataJSON or another format that only loads primitive types, as the Ruby documentation advises

Two details catch teams out. PHP's allowed_classes defaults to true when omitted, so a call without options accepts every class. And in .NET, Microsoft notes that even DataContractSerializer can be subverted if the type passed to its constructor comes from data an attacker can change, such as a type name read from a database.

Language-specific depth sits in the Java and Spring Security Guide, the .NET Security Guide, the Python Security Guide and the PHP and WordPress Security Guide.

Designing the data contract

Safe loaders are half the job. The other half is a contract that keeps the deserialised result small, predictable and validated before business logic sees it.

  • Separate transfer objects from domain objects: deserialise into DTOs with only primitive fields, collections of primitives and other DTOs. Map to domain objects in code after validation, so no constructor, setter or callback with side effects runs on raw input.
  • Close the schema: reject unknown fields rather than ignoring them. In JSON Schema that means "additionalProperties": false and an explicit required list; in Jackson, keep FAIL_ON_UNKNOWN_PROPERTIES enabled for external APIs. Unknown-field tolerance is how mass assignment and type smuggling slip through.
  • Bound resources before parsing: cap request size at the edge, then set parser limits. Java filters support maxbytes, maxdepth, maxrefs and maxarray; PHP unserialize() has max_depth (default 4096, added in PHP 7.4); the OWASP cheat sheet adds that stream size must be bounded separately because filters are not called for every primitive value.
  • Version explicitly: carry a schema version field and reject versions you no longer support. Silent fallback to a permissive legacy path is a common way old native formats survive a migration.
  • Do not persist native object graphs: sessions, caches and queues outlive code. Store JSON or Protocol Buffers so a later reader is not forced to trust whatever wrote the bytes years ago.
  • Treat model files as code: pickle-based model formats execute on load. Prefer weight-only formats and follow the Model Supply Chain Guide.

Integrity protection and the keys behind it

When state must round-trip through a client (view state, signed cookies, licence responses, cached tokens), signing is the standard answer: CWE-502 lists HMAC signing and sealing, and the Python pickle documentation suggests hmac when data must not be tampered with. Signing changes the question from "is this payload safe?" to "is the key still secret?", and that second question is an identity problem.

  • Machine keys are machine credentials: in February 2025 Microsoft Threat Intelligence reported more than 3,000 publicly disclosed ASP.NET machine keys copied from documentation and repositories, which let an attacker forge valid ViewState and load a post-exploitation framework. See the ASP.NET machine key attacks write-up.
  • Verify before you parse, and still parse safely: check the MAC over the raw bytes in constant time, then deserialise into fixed types. If the key leaks, the type restriction is what keeps a forged payload from becoming code execution.
  • One key per application and environment: generate keys, never copy them; store them in a secrets manager or protected configuration; never commit them. See the Secrets Management Guide.
  • Rotate on compromise, not only on schedule: if a host that can read the key is compromised, patching does not evict an attacker who holds the key. Rotate across every node in the farm together and restart the workers that cache it.
  • Prefer asymmetric signatures across trust boundaries: where one party issues and many verify (licence servers, update feeds), verifiers should hold only a public key, so a compromised verifier cannot mint payloads.

Rolling out Java serialisation filters

For Java estates that cannot remove ObjectInputStream quickly, the JDK filter mechanism (JEP 290, with filter factories added in JDK 17 by JEP 415) is the main control. Oracle's documentation sets out the semantics that matter for a safe rollout:

  1. Inventory first: list every readObject, readUnshared, XMLDecoder and RMI or JMX endpoint, and record whether its input crosses a trust boundary. Fix the untrusted ones by replacing the format where you can.
  2. Observe: set java.io.serialization.level = FINEST in conf/logging.properties on a pilot instance to log every filter decision, with a limits-only filter such as jdk.serialFilter=maxbytes=1048576;maxdepth=20;maxrefs=1000;maxarray=100000. Collect the classes actually deserialised over a full business cycle.
  3. Build the allowlist: write the observed packages as allow patterns and end with !*. Without the trailing reject, Oracle notes that a class matching no pattern is allowed, which turns the filter back into a denylist.
  4. Prefer per-stream filters: use ObjectInputFilter.Config.createFilter("com.example.dto.*;!*") and ois.setObjectInputFilter() where you own the code, keeping the JVM-wide property as a backstop.
  5. Merge, do not replace, in factories: if you set jdk.serialFilterFactory, have it merge the stream filter with the JVM-wide one. Oracle warns that returning only the requested filter disables the JVM-wide filter.
  6. Enforce in rings: drop logging to FINE (rejections only), enforce on one ring, alert on any rejection, then widen. Rollback is a configuration change: remove the trailing !* on the affected ring while the missing class is reviewed, never the whole filter.
  7. Cover the built-in endpoints: the RMI registry and DGC have built-in filters; JMX filtering is disabled by default and is enabled with com.sun.management.jmxremote.serial.filter.pattern.

Choosing between replace, restrict, sign and isolate

OptionChoose it whenTrade-offs
Replace with a data-only formatThe code is yours and the input is untrusted or might become soRemoves the class of bug; costs a migration and a dual-read period for stored data
Restrict types (filter, binder, find_class, allowed_classes)Migration will take quarters, or the format belongs to a third-party libraryDepends on a complete allowlist; gadgets in allowed classes still matter; needs monitoring for drift
Sign or seal the payloadState must round-trip through a client and you control both endsMoves the risk to key custody; useless after a key leak unless types are also restricted
Isolate the loaderYou must load untrusted native formats (for example, scanning uploaded model files)Sandbox, no network, no secrets in the process; operational overhead and latency
Virtual patch at the edgeAn exploited product is waiting for a vendor fixBuys days, not safety; encoded or compressed payloads bypass signature rules

Small teams: ban native deserialisers on untrusted paths with a lint or Semgrep rule in CI, pick one JSON library per language and pin its safe settings in a shared config. Large organisations: run an inventory across the portfolio, publish a supported-serialiser standard, set a JVM-wide filter in base images, and track BinaryFormatter removal as a programme with an end date tied to .NET 9 adoption.

Testing, detection and measurement

  • Static analysis: treat the unsafe APIs in the loader table as sinks and fail builds on new uses. CWE-502 rates automated static analysis as a high-effectiveness detection method. Pair it with the review approach in the Secure Code Review Guide.
  • Dependency checks: flag fastjson below 1.2.68, XStream below 1.4.17, YamlBeans below 1.16 and Kryo below 5 with registration off; these versions accept arbitrary classes by default according to the OWASP cheat sheet.
  • Safe dynamic tests: in authorised testing, send benign type names that should be rejected and confirm the rejection is logged; do not use live gadget chains in production.
  • Runtime telemetry: collect Java filter rejections from java.io.serialization, Python pickle.find_class audit events, PHP objects arriving as __PHP_Incomplete_Class, and .NET exceptions from BinaryFormatter calls after upgrading.
  • Post-exploitation signals: exploitation is usually T1190 Exploit Public-Facing Application followed by a shell child process of the web or application server (T1059) or a dropped T1505.003 Web Shell. Alert on interpreter processes spawned by w3wp.exe, java or php-fpm, and on reads of key configuration files.

Metrics that show the programme is working:

  • Number of native deserialisation sinks reachable from untrusted input (target zero), trended monthly.
  • Percentage of JVMs running with an enforcing filter ending in !*.
  • BinaryFormatter and sibling formatter call sites remaining, and services still blocked from moving to .NET 9.
  • Filter or binder rejections per week, with each one triaged as attack, bug or missing allowlist entry.
  • Signing keys that are unique, vaulted and rotated within policy, as a share of all serialisation keys.

Framework mapping

FrameworkReferenceRelevance
OWASP ASVS 5.0V1.5.2; V1.5.3Allowlist object types or restrict client-defined types, never use mechanisms defined as insecure; parse consistently across parsers
OWASP ASVS 5.0V1.3.2Avoid eval() and dynamic code execution features, the same class of risk as object callbacks
MITRE CWE / CAPECCWE-502; CAPEC-586 Object InjectionWeakness and attack pattern definitions
NIST SP 800-53 Rev. 5SI-10, SI-10(5), SI-7, SA-8, SA-11, SC-12Input validation and approved formats; integrity checks; engineering principles; developer testing; key management for signing keys
NIST CSF 2.0PR.PS-06; DE.CM-09Secure development practice; monitoring runtime environments
ISO/IEC 27001:2022 Annex AA.8.28 Secure coding; A.8.29 Security testing in development and acceptanceCoding standard and test gate for serialisation rules
MITRE ATT&CK v20T1190; T1059; T1505.003Initial access through exploitation, execution and persistence that follow

Common failure patterns

  • Checking the type after the call: Microsoft's guidance is explicit that inspecting an object returned by Deserialize() is too late, because execution may already have happened during construction.
  • Filters without a closing reject: a Java pattern list that does not end in !* allows every unlisted class.
  • Trusting a binder to save BinaryFormatter: Microsoft states denial of service cannot be mitigated with a SerializationBinder and does not commit to patching every bypass.
  • Shared or sample signing keys: keys copied from documentation, or one key across many tenants, turn a single leak into forged payloads everywhere.
  • "Internal only" queues and caches: Microsoft notes that payloads often cross a trust boundary without the developer realising it. A compromised neighbour service writes to the same Redis or Kafka topic.
  • Disabling safe mode to fix an error: switching to yaml.Loader, turning on autotype or setting TypeNameHandling.Auto to make one payload load reopens the whole class.

Lessons from incidents

  • ToolShell (2025): attackers chained an authentication bypass with SharePoint deserialisation (CVE-2025-49704, then the bypass CVE-2025-53770), stole the ASP.NET ValidationKey and DecryptionKey through a web shell, and could keep forging accepted ViewState after patching until keys were rotated. See ToolShell SharePoint Exploitation 2025. Lesson: patch, rotate keys, and treat every secret the process could read as exposed.
  • Fortra GoAnywhere MFT (2023 and 2025): CISA's Known Exploited Vulnerabilities catalogue describes CVE-2023-0669 as pre-authentication code execution through deserialising an attacker-controlled object in the License Response Servlet, and CVE-2025-10035 as deserialisation reachable by an actor with a validly forged licence response signature. Both are marked as known to be used in ransomware campaigns. Lesson: a signature check in front of a native deserialiser is only as strong as the signing key.
  • The pattern is common: 62 of the 1,754 entries in the CISA KEV catalogue (version 2026.10.21) describe deserialisation of untrusted data, across products from Oracle WebLogic to Telerik UI, Sitecore and SolarWinds Web Help Desk. Deserialisation flaws in internet-facing products are reliably weaponised.

Practitioner checklist

  • Inventory every deserialisation call and classify its input as trusted or untrusted, including caches, queues, cookies and uploaded files.
  • Move untrusted paths to fixed-type or closed-polymorphism data formats with closed schemas and size limits.
  • Pin fail-closed settings for each library in shared configuration and block unsafe APIs in CI.
  • Remove BinaryFormatter and its four sibling formatters before the service moves to .NET 9.
  • Deploy Java filters in observe mode, then enforce with an allowlist ending in !*, ring by ring.
  • Generate unique signing and machine keys per application, store them in a secrets manager and rotate them after any host compromise.
  • Set PHP allowed_classes on every remaining unserialize() call and use yaml.safe_load() everywhere in Python.
  • Alert on filter rejections and on shells spawned by application server processes.
  • Track the five metrics above and report sink count and key hygiene quarterly.

Standards and references

Related NHI Mgmt Group resources: Insecure Deserialisation Guide · Input Validation and Output Encoding Guide · Secrets Management Guide · Secure Coding Guide · Model Supply Chain Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 26 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.