Application Security

Parsing Untrusted Data in PHP, Python and JavaScript: unserialize, pickle, YAML and Prototype Pollution, From the Defender's Side

Every language has one parser that runs code while it reads. I tested the defensive side of each in PHP 8.6, Python 3.15 and Node 26: an ordinary destructor running on sender-controlled data, an allow-list unpickler rejecting a harmless datetime, a one-key JSON body adding isAdmin to every...

The most dangerous line in a web app is usually not a SQL query or a shell call. It's a parser: unserialize($cookie), pickle.loads(message), yaml.load(config), or a deep-merge helper fed with JSON.parse(req.body). Each of them looks like reading data. In each case, the format can tell the runtime to create objects, call functions or modify shared state, and the sender chooses what's in it.

The attack details for these are well documented elsewhere, and I'm not going to add to them. This piece is about the defensive side, tested. For each language, here's what the dangerous parser actually does with input you don't control, what the safe alternative does with the same input, and which defenses held up when I ran them on PHP 8.6.0, Python 3.15.2 and Node 26.13.1.

Parsing Untrusted Data Safely: The Map

Language Parser that can run code or change behavior What triggers it Safe default
PHP unserialize() Instantiates any loaded or autoloadable class, then runs __wakeup, __unserialize and later __destruct json_decode()
Python pickle.loads() Opcodes can import and call any global json.loads(), or signed data plus an allow-list unpickler
Python yaml.unsafe_load() / full Loader !!python/object/apply: tags call callables yaml.safe_load()
JavaScript Recursive merge or clone helpers on parsed JSON A __proto__ key writes to Object.prototype Null-prototype objects, key filtering, structuredClone
All three Any JSON parser Deep nesting goes to the stack, either the parser's or yours Depth and size limits at the edge

PHP: unserialize Runs Your Own Classes

You don't need a third-party gadget to see the problem. Here's an ordinary application class, the kind every codebase has, with a destructor that cleans up a file:

<?php
// An ordinary application class with a destructor, like a temp-file or cache handle.
class TempFile {
    public string $path = '/tmp/report.csv';
    public function __destruct() { echo "  TempFile::__destruct ran for path={$this->path}\n"; }
}

// Stand-in for a blob that came back from a cookie, cache or queue, where the sender controls the bytes.
$blob = 'O:8:"TempFile":1:{s:4:"path";s:25:"anything-the-sender-chose";}';
echo "serialized: $blob\n";

echo "unserialize(\$blob):\n";
$obj = unserialize($blob);
echo "  got ", get_class($obj), "\n";
unset($obj);

echo "unserialize(\$blob, ['allowed_classes' => false]):\n";
$obj = unserialize($blob, ['allowed_classes' => false]);
echo "  got ", get_class($obj), "\n";
unset($obj);

echo "json_decode of the same data as JSON:\n";
var_dump(json_decode('{"path":"anything-the-sender-chose"}', true));
serialized: O:8:"TempFile":1:{s:4:"path";s:25:"anything-the-sender-chose";}
unserialize($blob):
  got TempFile
  TempFile::__destruct ran for path=anything-the-sender-chose
unserialize($blob, ['allowed_classes' => false]):
  got __PHP_Incomplete_Class
json_decode of the same data as JSON:
array(1) {
  ["path"]=>
  string(25) "anything-the-sender-chose"
}

With a plain unserialize(), PHP created a real TempFile and set $path to whatever the sender put in the string. When the object went out of scope, it ran the destructor on that path. The sender never ran any code of their own, yet they controlled the arguments to code that was already in your app. Swap "echo the path" for "delete the path" or "write to the path," and that's the whole bug class. Real-world exploit chains just find existing classes that do something worse.

allowed_classes => false changed the outcome completely: PHP built a __PHP_Incomplete_Class instead, and no destructor ran. That's the option to use if you're stuck reading legacy serialized data. But PHP's own manual doesn't consider it sufficient: "Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading." Use json_decode(), which, as the last block shows, gives you plain arrays and nothing else.

Where serialized PHP data sneaks in: session handlers that store serialize() output, cache layers, queue payloads, "remember me" cookies, and phar:// paths, which deserialize their metadata when a filesystem function touches them on older PHP versions. Treat any of those, once an outsider can write to them, as untrusted.

We recommend reading What is Django? The Python Framework That Runs Instagram to continue reading our selection of content. Frameworks make this choice for you in their session and cache layers, and Django's defaults are a good example to compare against.

What is Django? The Python Framework That Runs Instagram Django is the Python web framework that ships with an ORM, admin panel, authentication, and migrations out of the box. SudoSecurity · Santhdium

Python: pickle Is a Program, Not a File Format

The Python docs put it as bluntly as documentation gets:

The pickle module is not secure. Only unpickle data you trust. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling.

A pickle is a sequence of opcodes for a small stack machine, and one of those opcodes imports any global by name. I won't build a malicious one. The defensive point shows up just as clearly with a harmless pickle. Here's the docs' "Restricting Globals" pattern, an Unpickler that only allows what you list:

import datetime, io, pickle

class AllowListUnpickler(pickle.Unpickler):
    """The pattern from the pickle docs' "Restricting Globals" section."""
    ALLOWED = {("builtins", "set"), ("builtins", "frozenset")}

    def find_class(self, module, name):
        if (module, name) in self.ALLOWED:
            return super().find_class(module, name)
        raise pickle.UnpicklingError(f"global '{module}.{name}' is forbidden")

blob = pickle.dumps({"when": datetime.datetime(2026, 11, 24), "tags": {"a", "b"}})
print("pickle.loads:", pickle.loads(blob))
try:
    AllowListUnpickler(io.BytesIO(blob)).load()
except pickle.UnpicklingError as e:
    print("AllowListUnpickler:", e)
pickle.loads: {'when': datetime.datetime(2026, 11, 24, 0, 0), 'tags': {'a', 'b'}}
AllowListUnpickler: global 'datetime.datetime' is forbidden

A dict holding a datetime and a set asked the unpickler to import datetime.datetime. Plain pickle.loads did it without asking. The allow-list unpickler refused, because datetime wasn't on the list. That's the exact mechanism that makes pickle dangerous: every class reference is a lookup the sender controls, and find_class is the one place you can say no. Even with an allow-list, the docs recommend signing the data (hmac) so you only unpickle what you produced. For anything crossing a trust boundary, the right answer is JSON or MessagePack, which have no way to express "call this."

Watch for pickle in places that don't say "pickle": pandas.read_pickle, joblib.load, torch.load on older settings, shelve, multiprocessing queues, and cache backends that pickle values by default.

YAML has the same split. PyYAML 6 removed the unsafe default:

PyYAML 6.0.4
yaml.load(doc): TypeError: load() missing 1 required positional argument: 'Loader'
yaml.safe_load(doc): ConstructorError - could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:datetime.date'
yaml.unsafe_load(doc): {'when': datetime.date(2026, 11, 24)}  <- it called datetime.date(2026, 11, 24)

yaml.load(doc) with no Loader is a TypeError now. safe_load refused the python/object/apply tag outright. unsafe_load did exactly what the tag said and called datetime.date(2026, 11, 24). A harmless callable here, any callable in general. Use safe_load for everything that isn't your own config file, and preferably for that too.

JavaScript: Prototype Pollution Through a One-Key Body

JavaScript's JSON.parse can't run code. What it can do is hand you an object with a key named __proto__, and the danger is in what your own code does next. Here's a recursive merge like the ones found in config loaders and "deep extend" helpers, plus three defenses:

// A naive recursive merge, the kind found in config loaders and "deep extend" helpers.
function merge(target, source) {
  for (const key of Object.keys(source)) {
    if (typeof source[key] === "object" && source[key] !== null) {
      if (typeof target[key] !== "object" || target[key] === null) target[key] = {};
      merge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

const body = JSON.parse('{"theme": "dark", "__proto__": {"isAdmin": true}}');
console.log("JSON.parse keeps __proto__ as an own key:", Object.keys(body));

merge({}, body);
console.log("after merge, a brand-new {} has isAdmin =", ({}).isAdmin);
delete Object.prototype.isAdmin;

// Defense 1: skip the dangerous keys.
function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
    if (typeof source[key] === "object" && source[key] !== null) {
      if (typeof target[key] !== "object" || target[key] === null) target[key] = Object.create(null);
      safeMerge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}
safeMerge({}, body);
console.log("after safeMerge, ({}).isAdmin =", ({}).isAdmin);

// Defense 2: objects with no prototype can't reach Object.prototype at all.
const settings = Object.create(null);
merge(settings, body);
console.log("merge into Object.create(null): ({}).isAdmin =", ({}).isAdmin, "| settings has own __proto__ key:", Object.hasOwn(settings, "__proto__"));
delete Object.prototype.isAdmin;

// Defense 3: structuredClone copies data, not prototypes.
const cloned = structuredClone(body);
console.log("structuredClone keeps __proto__ as data:", Object.keys(cloned), "| ({}).isAdmin =", ({}).isAdmin);
JSON.parse keeps __proto__ as an own key: [ 'theme', '__proto__' ]
after merge, a brand-new {} has isAdmin = true
after safeMerge, ({}).isAdmin = undefined
merge into Object.create(null): ({}).isAdmin = undefined | settings has own __proto__ key: true
structuredClone keeps __proto__ as data: [ 'theme', '__proto__' ] | ({}).isAdmin = undefined

JSON.parse itself is safe: it creates __proto__ as an ordinary own key, which is why Object.keys(body) lists it. The naive merge turns that key into a write. target["__proto__"] on a normal object is Object.prototype, so the merge recursed into it and set isAdmin = true there. After that, every object in the process inherited isAdmin: ({}).isAdmin returned true for an object created on the next line. Any check like if (user.isAdmin) on an object that never set its own value now passes.

All three defenses worked:

  • Key filtering: skip __proto__, constructor and prototype in any code that copies keys from input.
  • Null-prototype objects: Object.create(null) has no prototype chain to reach. The merge just stored __proto__ as an ordinary key.
  • structuredClone: copies data, not prototype links, and kept __proto__ as plain data.

Node also has a process-wide switch:

JSON.parse keeps __proto__ as an own key: [ 'theme', '__proto__' ]
after merge, a brand-new {} has isAdmin = undefined
after safeMerge, ({}).isAdmin = undefined

With --disable-proto=delete, the __proto__ accessor doesn't exist, so the same naive merge couldn't pollute anything. That's a cheap safety net for servers. Test it first, because some old libraries rely on __proto__ working.

And validate the shape of input before it reaches any merge. A schema validator such as Zod, Ajv or Valibot that only allows known keys stops this class of bug at the door. TypeScript types don't help here: they disappear at runtime, and JSON.parse returns any.

We recommend reading What is TypeScript? Why I Finally Stopped Fighting the Type System to continue reading our selection of content. Types are a compile-time promise, and this explains what they do and don't check.

What is TypeScript? Why I Finally Stopped Fighting the Type System What TypeScript is and why it's worth it: static types on top of JavaScript, the bugs they catch, and how to adopt them without fighting the compiler. SudoSecurity · Santhdium

Validating the Shape Before Anything Else Touches It

Every defense above protects one specific parser or helper. A schema check at the edge protects all of them at once, because nothing the schema doesn't name gets any further. Here's the same polluting body run through Zod 4.6.7:

import { z } from "zod";

const body = JSON.parse('{"theme": "dark", "__proto__": {"isAdmin": true}, "extra": 1}');

const Settings = z.object({ theme: z.enum(["light", "dark"]) });          // unknown keys are stripped
const StrictSettings = z.strictObject({ theme: z.enum(["light", "dark"]) }); // unknown keys are an error

const parsed = Settings.parse(body);
console.log("z.object().parse:", JSON.stringify(parsed), "| own keys:", Object.keys(parsed));

const strict = StrictSettings.safeParse(body);
console.log("z.strictObject().safeParse success:", strict.success, "|", strict.success ? "" : strict.error.issues.map((i) => `${i.code}: ${i.keys ?? i.message}`).join("; "));

const bad = Settings.safeParse({ theme: "purple" });
console.log("theme 'purple':", bad.success, "|", bad.success ? "" : bad.error.issues[0].message);
z.object().parse: {"theme":"dark"} | own keys: [ 'theme' ]
z.strictObject().safeParse success: false | unrecognized_keys: __proto__,extra
theme 'purple': false | Invalid option: expected one of "light"|"dark"

z.object() returned only theme. The __proto__ and extra keys were stripped, so a merge downstream had nothing dangerous to copy. z.strictObject() went further and rejected the whole request, naming both unknown keys, which is what you want on an API where an unexpected key means a buggy or hostile client. And a value outside the allowed set was rejected with a readable message.

The same idea exists in the other two languages: Pydantic models in Python ignore unknown fields by default or forbid them with extra="forbid", and in PHP a hand-written allow-list or a validator such as Symfony Validator does the job. The order is the point: parse with a data-only parser, validate against a schema that lists every allowed key, and only then let the value reach merges, ORMs or templates.

Depth: Three Parsers, Three Failure Modes

Every format here, JSON included, can nest without limit, and nesting eventually means stack frames somewhere. I fed each parser 100,000 nested arrays:

json.loads, 100,000 levels: RecursionError: Stack overflow (used 8124 kB) while decoding a JSON array from a unicode string
NULL
json_decode, 100,000 levels: Maximum stack depth exceeded near location 1:512 (default depth 512)
with JSON_THROW_ON_ERROR: JsonException: Maximum stack depth exceeded near location 1:512
JSON.parse, 100,000 levels: parsed
JSON.parse, 10,000,000 levels: parsed
JSON.stringify of the 100,000-level value: ok
Result What that means
PHP json_decode Returns NULL: "Maximum stack depth exceeded near location 1:512" A hard default depth of 512. Use JSON_THROW_ON_ERROR so the NULL isn't mistaken for a JSON null
Python json.loads RecursionError: Stack overflow (used 8124 kB) Fails safely, but as an exception your handler has to catch
Node JSON.parse Parsed, even at 10,000,000 levels The parser is fine. Your code isn't (see below)

Node's parser handled any depth I gave it. Then I walked the result the way most application code does, recursively:

recursive depth(): RangeError: Maximum call stack size exceeded

The depth problem didn't go away. It moved from the parser to the first recursive function that touched the value: a validator, a merge, a logger or a serializer. The defense is the same in all three languages: cap request body size at the proxy or framework, and cap nesting depth before any recursive code touches the value. PHP does this for you at 512. In Python and Node, you add it yourself.

What This Doesn't Cover

  • Exploit chains. No gadget chains, payloads or library-specific triggers here, by design. PHPGGC, ysoserial-style tooling and the CVE write-ups cover the offensive side.
  • XML. XXE and entity expansion ("billion laughs") are the same class of problem in another format, and deserve their own test of libxml, lxml and fast-xml-parser defaults.
  • Java and .NET deserialization. Same idea, bigger blast radius.
  • Template injection. Twig, Jinja2 and Handlebars rendering user-controlled templates is the parser-runs-code problem one layer up.

The Actual Point

There's one rule for all three languages: data from outside goes through a parser that can only produce data. That means JSON (json_decode, json.loads, JSON.parse) or yaml.safe_load, then a schema check, then your code. PHP's unserialize and Python's pickle hand the sender the controls of your own classes and functions, and an allow-list is a mitigation for legacy data, not a fix. JavaScript's parser is safe, and the trouble comes from merge helpers, which a null prototype, a key filter or --disable-proto=delete will stop. And limit depth everywhere, because a parser that accepts anything just moves the stack overflow into your own code.

Sources: php.net's unserialize() manual, the Python pickle documentation (including "Restricting Globals"), PyYAML 6's loader behavior, and the Node.js CLI documentation for --disable-proto. All tests were run by me on php:8.6-cli, Python 3.15.2 with PyYAML 6.0.4, and node:26-slim. Every script and output block above is reproduced verbatim from those runs. The scripts are original defensive teaching code and contain no exploit payloads.

$ tail -f /forums

Discussion

Comments live on the community forums — sign in there to reply.