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()withallowed_classes, Newtonsoft Json.NET withTypeNameHandling.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.serializationlogger; 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 authority | Typical examples | What an attacker controls | Use 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 schema | Field values only | Yes, with validation and size limits |
| Closed polymorphism (declared subtypes by logical name) | System.Text.Json [JsonDerivedType], Jackson @JsonTypeInfo(use = Id.NAME) with @JsonSubTypes | A choice among types the developer listed | Yes, 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 allowlist | Any class on the classpath that the library will load | No, unless a strict allowlist is enforced before instantiation |
| Native object graphs | Java ObjectInputStream, .NET BinaryFormatter, Python pickle, PHP unserialize(), Ruby Marshal.load | Class choice plus the callbacks those classes run during reconstruction | No. 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 loader | Unsafe usage | Fail-closed configuration |
|---|---|---|
Java ObjectInputStream | Any 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 databind | Default typing, or @JsonTypeInfo(use = Id.CLASS) on fields of type Object | No polymorphism, or Id.NAME with @JsonSubTypes; if default typing is unavoidable, activateDefaultTyping() with a restrictive PolymorphicTypeValidator |
| SnakeYAML | Default constructor on untrusted YAML | org.yaml.snakeyaml.constructor.SafeConstructor |
| XStream | Versions before 1.4.17, or relaxed security framework | 1.4.17 or later with the default allowlist kept, adding only your own types |
| Kryo | Class registration turned off | Registration required (the default from v5.0.0) |
| fastjson / fastjson2 | fastjson below 1.2.68; autotype enabled | fastjson 1.2.68+ with safemode on, or fastjson2 with autotype off |
| .NET BinaryFormatter, SoapFormatter, NetDataContractSerializer, LosFormatter, ObjectStateFormatter | Any use; Microsoft says the four siblings perform unrestricted polymorphic deserialisation like BinaryFormatter | Migrate to System.Text.Json, XmlSerializer or DataContractSerializer; a SerializationBinder is not a fix |
| Newtonsoft Json.NET | TypeNameHandling other than None | TypeNameHandling.None; if types must travel, a custom SerializationBinder allowlist |
| System.Text.Json (.NET 7+) | Custom converters that call Type.GetType() on a payload value | Built-in polymorphism only accepts derived types declared with [JsonDerivedType] |
| Python pickle, jsonpickle | pickle.loads() or jsonpickle.decode() on anything that could be tampered with | json plus schema validation; for legacy internal pickles, a RestrictedUnpickler overriding find_class() |
| PyYAML | yaml.load() with Loader=yaml.Loader or UnsafeLoader, yaml.unsafe_load() | yaml.safe_load() |
PHP unserialize() | Default call, which accepts all classes | json_decode(); for internal data, ['allowed_classes' => false, 'max_depth' => 64]. The manual warns not to pass user input even with allowed_classes |
Ruby Marshal.load | Any user-supplied or untrusted data | JSON 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": falseand an explicitrequiredlist; in Jackson, keepFAIL_ON_UNKNOWN_PROPERTIESenabled 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,maxrefsandmaxarray; PHPunserialize()hasmax_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:
- Inventory first: list every
readObject,readUnshared,XMLDecoderand RMI or JMX endpoint, and record whether its input crosses a trust boundary. Fix the untrusted ones by replacing the format where you can. - Observe: set
java.io.serialization.level = FINESTinconf/logging.propertieson a pilot instance to log every filter decision, with a limits-only filter such asjdk.serialFilter=maxbytes=1048576;maxdepth=20;maxrefs=1000;maxarray=100000. Collect the classes actually deserialised over a full business cycle. - 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. - Prefer per-stream filters: use
ObjectInputFilter.Config.createFilter("com.example.dto.*;!*")andois.setObjectInputFilter()where you own the code, keeping the JVM-wide property as a backstop. - 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. - 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. - 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
| Option | Choose it when | Trade-offs |
|---|---|---|
| Replace with a data-only format | The code is yours and the input is untrusted or might become so | Removes 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 library | Depends on a complete allowlist; gadgets in allowed classes still matter; needs monitoring for drift |
| Sign or seal the payload | State must round-trip through a client and you control both ends | Moves the risk to key custody; useless after a key leak unless types are also restricted |
| Isolate the loader | You 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 edge | An exploited product is waiting for a vendor fix | Buys 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, Pythonpickle.find_classaudit 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,javaorphp-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
| Framework | Reference | Relevance |
|---|---|---|
| OWASP ASVS 5.0 | V1.5.2; V1.5.3 | Allowlist object types or restrict client-defined types, never use mechanisms defined as insecure; parse consistently across parsers |
| OWASP ASVS 5.0 | V1.3.2 | Avoid eval() and dynamic code execution features, the same class of risk as object callbacks |
| MITRE CWE / CAPEC | CWE-502; CAPEC-586 Object Injection | Weakness and attack pattern definitions |
| NIST SP 800-53 Rev. 5 | SI-10, SI-10(5), SI-7, SA-8, SA-11, SC-12 | Input validation and approved formats; integrity checks; engineering principles; developer testing; key management for signing keys |
| NIST CSF 2.0 | PR.PS-06; DE.CM-09 | Secure development practice; monitoring runtime environments |
| ISO/IEC 27001:2022 Annex A | A.8.28 Secure coding; A.8.29 Security testing in development and acceptance | Coding standard and test gate for serialisation rules |
| MITRE ATT&CK v20 | T1190; T1059; T1505.003 | Initial 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
SerializationBinderand 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 settingTypeNameHandling.Autoto 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_classeson every remainingunserialize()call and useyaml.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
- MITRE: CWE-502 Deserialization of Untrusted Data
- OWASP: Application Security Verification Standard 5.0
- OWASP: Deserialization Cheat Sheet
- Oracle: Java SE 17 Serialization Filtering
- Microsoft: Deserialization risks in use of BinaryFormatter and related types
- Microsoft: How to serialize properties of derived classes with System.Text.Json
- Python Software Foundation: pickle, Python object serialization
- PHP: unserialize
Related NHI Mgmt Group resources: Insecure Deserialisation Guide · Input Validation and Output Encoding Guide · Secrets Management Guide · Secure Coding Guide · Model Supply Chain Guide