Deserialization is a trust boundary where bytes become objects, and some object models can carry behavior. If an attacker controls the serialized form and the library instantiates functions, classes or tags, data becomes code before any authorization check runs.
Unsafe deserializers do more than parse: they reconstruct types, call constructors, resolve magic methods or evaluate tagged values. Markers such as node-serialize's _$$ND_FUNC$$_, YAML's !!js/function or an eval field turn a cookie into a code path. Because the payload executes during session loading, it often runs before authentication, logging or input validation.
The developer sees a convenient session helper. The attacker sees a parser that will rebuild anything the client sends, including behavior the developer never intended to expose.
What is actually at stake?
Before touching a payload, map the assets, the actors and the boundary that is supposed to protect them. A finding only becomes a vulnerability when you can connect the failed boundary to a real asset.
Assets
- Session state and authentication decisions
- Environment variables and application secrets
- Files readable by the application user
- Internal network reachability and cloud metadata credentials
Actors
- Unauthenticated attacker who can set a cookie or submit a form
- Authenticated low-privilege user who can influence a stored object
- Attacker who can write to a queue, cache or import file consumed by a worker
- Malicious dependency or gadget chain present on the classpath
Trust boundaries
- Browser cookie to session middleware
- Request body to object mapper
- Queue message to background worker
- Uploaded file to import parser
- Application process to operating system and network
Abuse cases
- Place a function marker in a base64 cookie so the deserializer evaluates it
- Use a YAML tag that instantiates a function or class during load
- Supply an eval field that a later stage executes as JavaScript
- Chain a known gadget library to run a command during object reconstruction
- Store a malicious serialized object in a cache that another service later reads
Follow the decision, not the payload
Every family has a moment where trusted data becomes an authorization, parsing or state decision. Learn to point at that moment in the request path.
- 01
Accept
The application reads a cookie, hidden field, import file or queue message that the attacker can influence.
- 02
Decode
The transport wrapper such as base64, URL encoding or compression is removed; this is not a security control.
- 03
Rebuild
The deserializer reconstructs objects, resolves types and may evaluate function markers or magic methods.
- 04
Execute
Attacker-controlled behavior runs in the application process, often before authorization or logging.
- 05
Impact
The payload reads secrets, executes commands, reaches the network or changes application state.
node-serialize remote code execution, CVE-2017-5941
CVE-2017-5941, node-serialize unserialize code executionThe node-serialize library reconstructed JavaScript objects from JSON-like input and supported a function marker. When untrusted data was passed to unserialize, an attacker could embed an immediately invoked function expression.
Researchers showed that a payload containing the _$$ND_FUNC$$_ marker followed by a function expression executed when the library deserialized it. Applications that stored this value in a cookie exposed unauthenticated code execution.
Remote code execution as the Node.js process, enabling secret disclosure, file access and lateral movement. The exact impact depended on the privileges of the service account.
The deserializer treated a data format as executable code and offered no safe mode or type allowlist. The application passed client-controlled data directly to it.
Remove function support, use JSON.parse with a strict schema, never deserialize untrusted data into executable objects, and keep session state opaque and server-side.
Read it as a chain: discovery → failed decision → impact → fix. Then ask which link would have broken earliest.
A repeatable testing sequence
- Find every place where client-controlled bytes are deserialized: cookies, hidden fields, cache entries, queue messages and import files.
- Identify the library and version, then look for documented gadgets or function markers rather than guessing blindly.
- Decode and re-encode the container exactly; preserve signing or encoding layers if they are not checked.
- Build the smallest payload that returns a known value, then escalate to file read, environment access or command execution.
- Prove execution with a lab flag or a controlled side effect, and record which parser stage ran the code.
Where smart people get fooled
- base64 is an encoding, not a protection; anyone can decode and re-encode it.
- A JSON parser that only accepts literals is not automatically safe if a later stage eval's a field.
- A signature check on the cookie helps only if it is verified before deserialization, not after.
- A payload that crashes the parser may still be useful for denial of service, but it is not proof of code execution.
What would the logs show?
A control is stronger when someone can see it fail. These signals are starting points for a detection rule, not a complete SIEM use case.
- Cookies or bodies containing function markers, YAML tags, Java serialization magic bytes or pickle opcodes
- Deserialization exceptions followed by process crashes or unexpected child processes
- A session cookie whose length or entropy changes without a login
- Outbound connections or file reads immediately after a request with a serialized body
- Known gadget class names appearing in request payloads
index=app sourcetype=web | eval serialized=if(match(raw, "_\$\$ND_FUNC\$\$_|!!js/function|__FUNC__|rO0AB|ACED0005|gASV|__reduce__|__EVAL__"),1,0) | where serialized=1 | stats count values(uri) values(src_ip) by status | where count > 0Fix the decision, then prove it stays fixed
- Do not deserialize untrusted data into executable object graphs; use plain JSON with a strict schema and reject unknown fields.
- Use signed, opaque server-side sessions or encrypted tokens, and verify integrity before parsing.
- If a serializer is unavoidable, allowlist types, disable function and tag resolution, and run parsing in a sandbox with least privilege.
- Add monitoring for deserialization errors and unexpected child processes, and keep serialization libraries patched.
const session = unserialize(Buffer.from(cookie, 'base64').toString('utf8'));
if (session.role === 'admin') grantAdmin();const raw = verifySignedCookie(cookie, sessionKey);
if (!raw) return unauthorized();
const parsed = JSON.parse(raw);
const session = sessionSchema.parse(parsed);
if (session.role === 'admin' && await isCurrentAdmin(session.userId)) grantAdmin();Verify integrity before parsing, parse only plain JSON, enforce a strict schema, and authorize against current server-side state. Never let a serializer instantiate functions, classes or tags from untrusted input.
Regression tests a reviewer would ask for
Function marker is rejected
GivenA cookie containing _$$ND_FUNC$$_ and a function expression
WhenThe session middleware loads it
ThenThe request is rejected without evaluating the function
Signature checked before parse
GivenA modified signed cookie
WhenThe server verifies integrity
ThenVerification fails before any deserialization occurs
Unknown fields rejected
GivenA JSON session with an unexpected eval field
WhenThe schema validator runs
ThenValidation fails and no dynamic evaluation occurs
Least privilege
GivenA deserialization parser running in the application
WhenA malicious object is processed
ThenThe process cannot read unrelated secrets or spawn privileged commands
What this finding is not
Strong testers kill their own findings before someone else does. These are the shortcuts that turn a real bug into a weak report — or a false alarm into a wasted escalation.
- The cookie is base64 JSON and the application only calls JSON.parse; no function marker is evaluated.
- A payload causes a parser error or a 500 response but no code runs and no secret is returned.
- The value is signed and the signature is verified before parsing; tampering is rejected.
- The marker appears in a rendered page as text but is never passed to a deserializer.
Terms you should be able to use precisely
- Deserialization
- Reconstructing an object or data structure from a stored or transmitted representation.
- Gadget chain
- A sequence of existing classes and methods that, when deserialized, produces a security-relevant side effect.
- Magic method
- A language hook such as __wakeup or __destruct that runs automatically during object lifecycle events.
- Function marker
- A serializer-specific token that tells the parser to rebuild executable behavior rather than plain data.
- Type allowlist
- A policy that permits only known safe classes or fields during deserialization.
- Opaque session
- A random identifier stored server-side, so the client never controls the session object graph.
Answer these without reciting a payload
Why is base64-encoded JSON in a cookie still dangerous?
Base64 is reversible encoding, not protection. If the decoded value reaches an unsafe deserializer that evaluates markers or reconstructs behavior, the attacker controls code execution.
Does signing the cookie fix insecure deserialization?
Only if the signature is verified before deserialization and the parser is still safe. A valid signature on data produced by an unsafe serializer can still carry a gadget if the signing key is shared or the serializer is used elsewhere.
What is the strongest architectural fix?
Do not deserialize untrusted data into executable objects. Use opaque server-side sessions or strict JSON with a schema, and keep parsers in a least-privilege sandbox.
Can you separate the mechanism from the payload?
Four questions, graded on the server. Answers and explanations are released only after you submit, and signed-in learners keep a best score.
التسلسل غير الآمن يحوّل البيانات إلى سلوك. عندما يتحكم المهاجم في قيمة تُمرَّر إلى مكتبة تفكّك كائنات وتعيد بناء دوال أو وسوم أو فئات، فقد ينفّذ كودًا قبل أي تحقق من الصلاحية. Base64 ليس حماية. الحل المعماري هو جلسات خادم معتمة أو JSON صارم بمخطط، مع التحقق من التوقيع قبل التحليل، ورفض الحقول والأنواع غير المعروفة، وتعطيل الدوال والوسوم، وتشغيل أي تفكيك في بيئة محدودة الصلاحيات. راقب مؤشرات مثل _$$ND_FUNC$$_ وrO0AB و!!js/function، واختبر أن تعديل الكوكي يُرفض قبل الوصول إلى الـparser.
If the cookie is signed but the server deserializes before checking the signature, does signing actually protect the parser?