Insecure deserialization¶
When is it relevant¶
A new or changed code path that turns bytes from outside the process back into objects with a format that can name its own types. Examples:
- Python pickle, yaml.load, jsonpickle;
- Java ObjectInputStream, XStream, Jackson with default typing, SnakeYAML;
- .NET BinaryFormatter, Json.NET with TypeNameHandling;
- PHP unserialize and phar://;
- Ruby Marshal.load and YAML.unsafe_load;
- Node node-serialize, or js-yaml 3 with load.
The bytes can come from a request body, a cookie, a hidden form field, a file upload, a cache (Redis, memcached), a message queue, or a database column another component writes.
Attack¶
The attacker sends a serialized object instead of data. While it is being decoded, the library creates objects and calls their methods: constructors, __reduce__, readObject, __wakeup or __destruct, setters. Gadget chains in the app's own dependencies turn those calls into code execution, file writes or SSRF. Public tools build the payload for you: ysoserial for Java, ysoserial.net for .NET and PHPGGC for PHP. Even a format with no gadgets can be abused to set fields the code trusts, or to exhaust memory. Signing the data stops it only while the key stays secret.
Mitigation¶
- Don't deserialize untrusted data with a format that carries types. Use JSON or protobuf into explicit data classes, and validate the result.
- If a native format is unavoidable:
- Sign the data with an HMAC and verify the signature before decoding, with a key the client never sees.
- Restrict the classes that may be decoded with an allowlist: Java
ObjectInputFilter, a PythonUnpickler.find_classoverride, PHPallowed_classes. - Use the safe loader of each library:
yaml.safe_load,YAML.safe_load, SnakeYAMLSafeConstructor, Jackson without default typing, Json.NETTypeNameHandling.None. - Treat caches, queues and shared databases as untrusted unless only your service can write to them.
- Keep gadget-rich libraries up to date. Watch for deserialization advisories in commons-collections, Jackson, XStream, Json.NET and Psych.
Test¶
- Point-in-time: find every decode call and trace where its bytes come from. For each one reachable from outside, send a harmless gadget payload built for the stack's libraries, such as a DNS lookup or a sleep, and check that it's refused before any object is created.
- Continuous: a SAST rule for the dangerous decode calls. Add a unit test that the class allowlist or the signature check rejects an unexpected type or a tampered blob.
Examples¶
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
JSON.parse + schema validation |
Best option: JSON carries no types or functions | Zod, Ajv |
js-yaml 4 load (safe by default) |
YAML input | js-yaml |
| Signed or encrypted cookies | State round-tripped through the client | cookie-signature, iron-session |
Vulnerable — node-serialize (or funcster, serialize-to-js)
const serialize = require('node-serialize')
app.get('/profile', (req, res) => {
const prefs = serialize.unserialize(Buffer.from(req.cookies.prefs, 'base64').toString())
res.json(prefs)
})
node-serialize revives functions with eval. A value ending in () is called
while it is being decoded, which gives code execution (CVE-2017-5941).
Vulnerable — YAML with the unsafe schema
yaml.load(body) // js-yaml 3.x: !!js/function runs code
yaml.load(body, { schema: yaml.DEFAULT_FULL_SCHEMA })
Vulnerable — JSON merged into an object
JSON.parse itself is safe, but a deep merge or Object.assign of the result
is prototype pollution.
Mitigated — JSON + schema
const Prefs = z.object({ theme: z.enum(['light', 'dark']), pageSize: z.number().int().min(10).max(100) }).strict()
const prefs = Prefs.parse(JSON.parse(req.cookies.prefs ?? '{}'))
Docs: Zod
Mitigated — safe YAML
const yaml = require('js-yaml') // v4: load() uses the safe default schema
const doc = yaml.load(body)
Docs: js-yaml migration notes
Bypasses to check
- js-yaml pinned to 3.x, where
loadis unsafe andsafeLoadis the safe one. v8.deserializeorvmused to "revive" objects, andeval/new Functionon stored JSON-like strings.- Merging decoded input into objects (prototype pollution) and class-transformer
plainToInstanceinto classes with side effects. - Signed cookies whose secret is a default value or hard-coded.
What to grep for
unserialize(,node-serialize,funcster,serialize-to-js,cryoyaml.load(,DEFAULT_FULL_SCHEMA,js-yaml@3,v8.deserialize(eval(,new Function(,plainToInstance(,merge(,Object.assign(
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
JSON into explicit types (json, pydantic, dataclasses) |
Best option: any data that crosses a trust boundary | json, pydantic |
yaml.safe_load |
YAML config or uploads | PyYAML |
HMAC-signed blobs (itsdangerous, hmac) |
You must round-trip state through the client | itsdangerous |
Unpickler.find_class allowlist |
Legacy pickle you can't remove yet; a mitigation, not a fix | Restricting globals |
Vulnerable — pickle from a cookie
@app.get('/cart')
def cart():
items = pickle.loads(base64.b64decode(request.cookies['cart']))
return render_template('cart.html', items=items)
pickle calls __reduce__ on the way in, so a client-built object can return
(os.system, ('id',)) and run it. The
pickle docs say it plainly:
never unpickle data you don't trust.
Vulnerable — the "safe-looking" wrappers
yaml.load(request.data, Loader=yaml.Loader) # yaml.Loader / UnsafeLoader build any Python object
jsonpickle.decode(request.data) # JSON on the outside, pickle semantics inside
pd.read_pickle(uploaded_file) # pandas, joblib, torch.load(…) on model uploads
shelve.open(path) # pickle underneath
Vulnerable — a cache that anyone on the network can write to
Mitigated — JSON into a schema
class CartItem(BaseModel):
sku: constr(pattern=r'^[A-Z0-9-]{1,32}$')
qty: conint(ge=1, le=99)
items = TypeAdapter(list[CartItem]).validate_json(request.cookies.get('cart', '[]'))
JSON only produces dicts, lists, strings, numbers and booleans, so there is nothing to call during decoding. pydantic then checks the shape.
Docs: pydantic TypeAdapter
Mitigated — sign before you trust it
s = URLSafeSerializer(app.config['SECRET_KEY'], salt='cart')
items = s.loads(request.cookies['cart']) # raises BadSignature if tampered; JSON inside
itsdangerous verifies the HMAC first, and uses JSON, not pickle, by default.
Docs: itsdangerous URLSafeSerializer
Mitigated — safe_load for YAML
Docs: PyYAML safe_load
Bypasses to check
- An HMAC checked after
pickle.loads, or compared with==instead ofhmac.compare_digest. - A signing key that is hard-coded, shared with another service, or leaked through an error page. The same applies to Flask's
SECRET_KEYwhen sessions use a pickle serializer. - A
find_classallowlist that permitsbuiltins,os,subprocess,functools.partialor any module with a callable that runs code. numpy.load(allow_pickle=True),torch.loadwithoutweights_only=True, andjoblib.loadon uploaded model files.- Data written by another service, such as a worker or a queue, that a user can influence.
What to grep for
pickle.loads(,pickle.load(,cPickle,_pickle,dill.,shelve.,marshal.loads(yaml.load(,Loader=yaml.Loader,UnsafeLoader,FullLoader,yaml.unsafe_load(jsonpickle.decode(,pd.read_pickle(,joblib.load(,torch.load(,np.load(,allow_pickle=True
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
| JSON into explicit DTOs (Jackson without default typing) | Best option: any data across a trust boundary | Jackson polymorphic types |
ObjectInputFilter allowlist (JEP 290 / JEP 415) |
Legacy Java serialization you can't remove yet | ObjectInputFilter |
SnakeYAML SafeConstructor (or SnakeYAML 2.x defaults) |
YAML input | SnakeYAML |
XStream allowlist (allowTypes) |
XML object mapping | XStream security |
Vulnerable — ObjectInputStream on request data
@PostMapping("/import")
public void importState(HttpServletRequest req) throws Exception {
try (ObjectInputStream in = new ObjectInputStream(req.getInputStream())) {
State s = (State) in.readObject(); // the cast happens after every object is built
}
}
readObject builds the whole object graph first, calling readObject,
readResolve and the like on each class. With a gadget library on the
classpath (commons-collections, Spring, Groovy), a ysoserial payload runs a
command before the cast fails.
Vulnerable — Jackson default typing
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, DefaultTyping.EVERYTHING);
mapper.readValue(body, Object.class); // {"@class": "com.sun.rowset.JdbcRowSetImpl", ...}
The same happens with @JsonTypeInfo(use = Id.CLASS) on a field of type
Object or Serializable.
Vulnerable — SnakeYAML 1.x default constructor, XStream without a security setup
Mitigated — JSON into a DTO
record ImportRequest(@NotBlank String name, @Size(max = 100) List<@Valid Item> items) {}
@PostMapping("/import")
public void importState(@Valid @RequestBody ImportRequest body) { ... }
Docs: Spring @RequestBody
Mitigated — allowlist filter for legacy streams
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter("com.example.State;com.example.Item;java.base/*;!*");
in.setObjectInputFilter(filter);
Docs: Serialization filtering
Mitigated — safe YAML
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> doc = yaml.load(body);
Bypasses to check
- A cast or
instanceofcheck afterreadObject. The gadget has already run by then. - Filters written as a blocklist (
!org.apache.commons.collections.*) instead of an allowlist. New gadget chains appear all the time. - Hidden users of Java serialization: RMI, JMX, JMS
ObjectMessage, Hazelcast and Ehcache, andViewStatein JSF. - Jackson
@JsonTypeInfoon abstract orObjectfields, and old jackson-databind versions with known gadget CVEs.
What to grep for
ObjectInputStream,readObject(,readUnshared(,XMLDecoder,SerializationUtils.deserialize(activateDefaultTyping(,enableDefaultTyping(,@JsonTypeInfo,Id.CLASSnew Yaml(,XStream,fromXML(,Kryo,Hessian
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
System.Text.Json into explicit types |
Best option: it doesn't resolve types from the payload | System.Text.Json |
Json.NET with TypeNameHandling.None (the default) |
Existing Newtonsoft code | TypeNameHandling |
A SerializationBinder allowlist |
You really need polymorphic JSON | ISerializationBinder |
| Data Protection for round-tripped state | State sent to the client and back | Data Protection |
Vulnerable — BinaryFormatter (and its relatives)
Microsoft calls BinaryFormatter dangerous and impossible to secure, and
removed it in .NET 9. SoapFormatter, NetDataContractSerializer,
LosFormatter and ObjectStateFormatter have the same problem. ysoserial.net
builds payloads for all of them.
Vulnerable — Json.NET with type names from the payload
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };
var msg = JsonConvert.DeserializeObject<Message>(body, settings);
// {"$type": "System.Windows.Data.ObjectDataProvider, PresentationFramework", ...}
Mitigated — System.Text.Json into a record
public record CartItem(string Sku, int Qty);
var items = JsonSerializer.Deserialize<List<CartItem>>(body) ?? [];
Docs: JsonSerializer.Deserialize
Mitigated — polymorphism with an allowlist
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(EmailMessage), "email")]
[JsonDerivedType(typeof(SmsMessage), "sms")]
public abstract record Message;
The payload can only pick one of the listed types, by a short name. It never names a .NET type.
Docs: Polymorphic serialization
Bypasses to check
TypeNameHandlingset to anything other thanNone, globally or on one property with[JsonProperty(TypeNameHandling = ...)].- ASP.NET Web Forms
__VIEWSTATEwith a known or leakedmachineKey, which gives code execution throughObjectStateFormatter. DataContractSerializerwith known types from input, or withDataContractResolver.- Data Protection keys that are shared, or left in the default location of a container that gets rebuilt.
What to grep for
BinaryFormatter,SoapFormatter,NetDataContractSerializer,LosFormatter,ObjectStateFormatterTypeNameHandling,JavaScriptSerializerwith aSimpleTypeResolver,DataContractResolvermachineKey,__VIEWSTATE,XamlReader.Parse(
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
json_decode + validation |
Best option: JSON creates no objects of your classes | json_decode |
unserialize($data, ['allowed_classes' => false]) |
Legacy data you can't migrate yet | unserialize |
HMAC with hash_hmac + hash_equals before decoding |
Round-tripped state | hash_hmac |
Vulnerable — unserialize on a cookie
Decoding creates objects of any loaded class and later calls their
__wakeup, __destruct and __toString. PHPGGC has ready-made chains for
Laravel, Symfony, Monolog, Guzzle and more.
Vulnerable — phar:// on a user-controlled path
Before PHP 8.0, any filesystem function on a phar:// path deserialized the
phar's metadata, so an uploaded "image" acts as a serialized payload.
Mitigated — JSON
Docs: json_decode
Mitigated — legacy data: no classes, and a signature first
[$mac, $payload] = explode('.', $_COOKIE['cart'], 2) + [null, null];
if (!hash_equals(hash_hmac('sha256', $payload, $key), (string)$mac)) abort(400);
$cart = unserialize(base64_decode($payload), ['allowed_classes' => false]);
Bypasses to check
allowed_classesset to a list that includes a class with a dangerous__destruct, or left out.- Laravel's
APP_KEYleaked. Encrypted cookies are then decrypted and unserialized (CVE-2018-15133). phar://reachable throughfile_exists,getimagesize,fopenoris_diron PHP 7.x.- Session handlers that unserialize data from a shared Redis or database.
What to grep for
unserialize(,allowed_classes,__wakeup,__destruct,__unserializephar://,Phar::,file_exists(,getimagesize(with inputigbinary_unserialize(,msgpack_unpack(,yaml_parse(
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
JSON.parse into plain hashes, then validate |
Best option | JSON |
YAML.safe_load (YAML.load in Psych 4+) |
YAML input | Psych safe_load |
Rails MessageVerifier / encrypted cookies with the JSON serializer |
Round-tripped state | Rails cookies |
Vulnerable — Marshal.load on request data
Marshal.load rebuilds objects of any loaded class. Universal gadget chains for
Ruby 2.x and 3.x turn that into code execution.
Vulnerable — unsafe YAML
Vulnerable — Rails cookies with the Marshal serializer
Rails.application.config.action_dispatch.cookies_serializer = :marshal # or :hybrid reading old cookies
If secret_key_base leaks, every signed cookie becomes a Marshal.load
payload.
Mitigated — JSON
Mitigated — safe YAML with an explicit allowlist
Docs: Psych safe_load
Bypasses to check
permitted_classesthat includeSymbolwithStructorOpenStruct, or any class with dangerousinit_withor[]=methods.Oj.loadin:objectmode, andOxobject mode.- A leaked
secret_key_basetogether with:marshalor:hybridcookies, or cache stores (MemCacheStore,RedisCacheStore) that useMarshaland can be written by others.
What to grep for
Marshal.load(,Marshal.restore(,YAML.load(,YAML.unsafe_load(,Psych.load(cookies_serializer,:marshal,:hybrid,Oj.load(,mode: :objectsecret_key_base,MessageVerifier
Go's standard decoders (encoding/json, encoding/gob, encoding/xml) never
call methods on types the payload chooses, so there are no gadget chains like in
Java or PHP. The risks that remain are decoding into the wrong type, a sender
that chooses the concrete type of an interface, and inputs that use up memory.
Mitigation options
| Option | When it fits | Docs |
|---|---|---|
json.Decoder into a concrete struct with DisallowUnknownFields |
Best option | encoding/json |
http.MaxBytesReader around the body |
Every decoder fed from a request | MaxBytesReader |
| Signed or encrypted payloads | Round-tripped state | crypto/hmac, gorilla/securecookie |
Vulnerable — gob from the network into an interface
gob.Register(ShellTask{}) // a type whose Run() executes Cmd
var job Task // interface { Run() error }
gob.NewDecoder(conn).Decode(&job) // the sender picks ShellTask{Cmd: "…"}
job.Run()
gob doesn't execute anything itself. But any registered type can be chosen by the sender, and the code then calls its methods.
Vulnerable — unbounded decode
Mitigated — concrete type, size limit, strict fields
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var req struct {
Name string `json:"name"`
Items []Item `json:"items"`
}
if err := dec.Decode(&req); err != nil { http.Error(w, "bad request", 400); return }
Docs: Decoder.DisallowUnknownFields
Bypasses to check
- Decoding into
map[string]anyorany, then type-switching into behaviour. - YAML libraries with custom unmarshalers that do work (
UnmarshalYAMLthat opens files or URLs). - Decompressing untrusted input with no limit, such as
gzip.NewReaderfollowed byio.ReadAll.
What to grep for
gob.NewDecoder(,gob.Register(,json.Unmarshal(,Decode(&,any,interface{}yaml.Unmarshal(,UnmarshalYAML,UnmarshalJSON,MaxBytesReader,io.ReadAll(