--- name: sh-kb-deserialization description: "Knowledge base for finding insecure deserialization - untrusted data fed to object-deserialization APIs that can trigger RCE or object injection via gadget chains. Use when hunting deserialization issues. CWE-502, OWASP A08:2021-Software and Data Integrity Failures." --- # Insecure Deserialization - Hunter Knowledge Base Deserializing attacker-controlled bytes into live objects can execute code during reconstruction (magic methods / gadget chains) or corrupt application state. Confirmed native-object deserialization of untrusted input is typically critical (RCE). ## Sinks by ecosystem (grep targets) - **Python**: `pickle.load(s)`, `cPickle`, `yaml.load(` without `SafeLoader`, `jsonpickle.decode`, `shelve`, `dill`, `marshal.loads`, `pandas.read_pickle`, `numpy.load(allow_pickle=True)`. - **Java**: `ObjectInputStream.readObject(`, `readUnshared`, XMLDecoder, XStream (default), Kryo, SnakeYAML `new Yaml().load(`, Jackson polymorphic typing (`enableDefaultTyping`/`@JsonTypeInfo`), Fastjson `parseObject` with autotype. - **PHP**: `unserialize(` on user input (POP chains via `__wakeup`/`__destruct`). - **Ruby**: `Marshal.load(`, `YAML.load(` (Psych, pre-safe), `Oj` in object mode. - **.NET**: `BinaryFormatter.Deserialize`, `LosFormatter`, `NetDataContractSerializer`, `TypeNameHandling` in JSON. - **Node**: `node-serialize` `unserialize(`, `funcster`, `serialize-javascript` misuse, `vm` on decoded input. - **Go**: `encoding/gob` into `interface{}` is type-limited but DoS-prone; `yaml.Unmarshal` into `interface{}` then used to pick types or call functions; plugin/RPC decoders keyed by a client-supplied type name. - **More Java**: `ObjectMapper.readValue` with a `Object`/`Serializable` target and default typing, `HessianInput`, `XMLDecoder`, `JNDI`/`InitialContext.lookup(user)` reached while deserializing, `SerializationUtils.deserialize` (Spring/Commons), RMI/JMX endpoints, JMS `ObjectMessage.getObject()`, Spring `HttpInvokerServiceExporter`, Java session stores (Redis/JDBC session replication), `ObjectInputStream` subclasses with a weak `resolveClass`. - **More .NET**: `JavaScriptSerializer` with a `SimpleTypeResolver`, `ObjectStateFormatter`, ViewState with `enableViewStateMac=false` or a known/leaked machineKey, `DataContractSerializer` with attacker-chosen `KnownTypes`, `Json.NET` `TypeNameHandling` other than `None`, `XmlSerializer` with an attacker-chosen `Type`. - **More PHP/Ruby**: `unserialize` reached via `phar://` wrapper on file functions (`file_exists`, `is_dir`, `getimagesize` on a user path), Laravel `decrypt()` with a leaked `APP_KEY`, Rails `Marshal`-backed cookies or cache with a leaked `secret_key_base`, `YAML.load_file`, `Oj.load` with `mode: :object`, `ERB`/`Psych` unsafe load. - **Format-level**: `ruamel.yaml` with the unsafe loader, XML parsers building typed objects (XStream, JAXB with `xsi:type`), `JSON` libs honouring `@type`/`$type`/`__class__` keys (fastjson, jsonpickle, Json.NET). ## Detection recipe 1. `graft grep "pickle.load|yaml.load\(|readObject|unserialize\(|Marshal.load|BinaryFormatter|TypeNameHandling|enableDefaultTyping" --json`. 2. Trace the input to the deserializer: request body/cookie/header, cache, queue message, uploaded file, or a signed token whose signature isn't verified before deserialization. 3. Check for a safe variant (see filters). If the raw/native deserializer processes untrusted bytes, flag. 4. Look for **indirect and second-order feeds**: Redis/Memcached/DB-cached objects, session stores, message queues (Celery/RQ with pickle serializer, JMS, RabbitMQ), job arguments, webhooks from "trusted" partners, files in shared storage or build artifacts, ML model files (`torch.load` without `weights_only=True`, `joblib.load`, `pickle`-based model formats), and import/restore/backup features. 5. Look for **signed-token bypass**: framework session/cookie formats that deserialize after a MAC check (Flask/itsdangerous, Rails, Laravel, ASP.NET ViewState). Safe only while the key is secret; check for default, committed, weak, or logged keys, and for code paths that deserialize before verifying. 6. Look for **non-RCE impact** where no gadget is known: attacker-chosen class instantiation (SSRF/file read via constructors or `JNDI`), property injection into privileged objects, DoS via nested/huge structures, and authz bypass through tampered serialized state (roles in a serialized session). 7. Grep config, not just code: `application.yml`/`settings.py` for `PICKLE`/`serializer`, Jackson `DEFAULT_TYPING`, `CELERY_ACCEPT_CONTENT`, `SESSION_SERIALIZER`, XStream security setup. ## Variant hunting Once one sink is found: grep every call of the same loader and the wrapper around it (`load_object`, `from_cache`, `deserialize_job`); find every producer that writes the format (whoever can write the cache/queue/file owns the sink); check sibling endpoints and message topics that share the consumer; check the same library elsewhere in the monorepo or in other services reading the same queue; for Java, check which gadget libraries are on the classpath (dependency manifests) to rate reachability; for PHP, list other file-system functions that accept `phar://`. ## Payloads / PoC - Python pickle: a class with `__reduce__` returning `(os.system, ('id',))` - describe the gadget; do not ship a live malicious blob. - Java: reference `ysoserial` gadget families (CommonsCollections, etc.) conceptually - the PoC is that the endpoint deserializes attacker bytes with vulnerable classpath gadgets present. - PHP: craft a serialized object of a class with a dangerous `__destruct`/`__wakeup` (POP chain). - Detection without RCE: send a malformed/DoS payload or an object of an unexpected type and observe type-confusion behavior. ## False-positive filters - **Safe loaders**: `yaml.safe_load`, `SafeLoader`; JSON (`json.loads`, `JSON.parse` of plain data) with no polymorphic typing; protobuf/avro/thrift schema-bound decoders; `pickle` of a **trusted, integrity-checked** source only (e.g. a file the app itself wrote, signature-verified before load). - Deserializer restricted by an allowlist of classes / `ObjectInputFilter` (Java) / custom `find_class`. - Data is signed+verified (HMAC) *before* deserialization and the key is secret. - The format is data-only: `json.loads`, `JSON.parse`, `yaml.safe_load`, protobuf; Jackson with typing off and a concrete target class; `ObjectMapper` with a `PolymorphicTypeValidator` allowlist; `torch.load(weights_only=True)`. - Source is only writable by a trusted component (private queue on an isolated network, file the app itself wrote) AND you can name why an attacker cannot reach it; "internal" alone is weak, see second-order feeds. - Real evidence of a finding: an attacker-reachable byte source flows to a native/polymorphic loader with no integrity check and no class allowlist. For Java/.NET/PHP, note which gadget-bearing libraries are present; absent any, rate as object injection or DoS and mark `needs-runtime`. ## Detection signals (for defenders) - **Logs needed**: web/proxy/WAF logs (request body size, content type, cookie/param lengths), application error logs (deserialization exceptions with class names), queue/broker logs, EDR process-creation and network events on the application host, egress firewall or DNS logs. - **Attempts**: spikes of `InvalidClassException`, `ClassNotFoundException`, `UnpicklingError`, `SerializationException`, `unserialize()` notices, ViewState MAC failures, or "type not allowed" errors tied to one source; request fields that start with serialization magic (Java `rO0`/`ac ed`, .NET `AAEAAAD`, PHP `O:`/`a:`, pickle protocol bytes) in places that normally carry plain tokens; oversized or deeply nested bodies. - **Success**: the application runtime process (java, python, php-fpm, w3wp, node, ruby) spawning a shell, interpreter, `curl`/`wget`, `whoami`, `id`, or a network tool; first-ever outbound connection or DNS lookup from the app server to an unfamiliar host right after a deserialization-related request; new files in web or temp directories written by the app user. - **Behaviour detection ideas**: (1) EDR parent-child rule: server/runtime process as parent of `sh`, `bash`, `cmd.exe`, `powershell.exe`, or download tools, correlated within seconds to an inbound request; (2) deserialization error burst from one client followed by a single successful request and new outbound connection from the host. - **ATT&CK**: T1190 (Exploit Public-Facing Application), T1059 (Command and Scripting Interpreter) for the resulting execution, T1505.003 (Server Software Component: Web Shell) when a shell is dropped. ## CWE / OWASP / severity CWE-502. OWASP A08:2021. Untrusted native deserialization with reachable gadgets -> **critical**; object injection with limited impact -> high. ## Chaining hints Deserialization RCE -> read `secrets`, pivot; often reachable via `access-control` gaps (an endpoint that accepts serialized state); cache/queue poisoning feeds it a stored payload (second-order). ## Mitigation Never deserialize untrusted data with native/polymorphic deserializers. Prefer schema-bound formats (JSON without type info, protobuf). If unavoidable, sign+verify integrity with a secret key and restrict to an allowlist of expected classes; disable polymorphic typing (Jackson `TypeNameHandling.None`, remove XStream default). Keep gadget-prone libraries patched.