guides · 2026-11-14
Why pickle.loads and yaml.load Turn User Data Into Code Execution
Published 2026-11-14 · Reviewed 2026-11-14 · By the Ingenious AI team
The short answer
Deserializers that reconstruct arbitrary objects execute attacker instructions during loading — before your code sees a single field. pickle.loads, yaml.load without SafeLoader, PHP unserialize and Java readObject on untrusted bytes are remote code execution by design, not by bug. Replace them with JSON or schema-validated formats for anything that crosses a trust boundary.
Check your own app free: paste your code or enter your site URL on the Vibe-Code Audit homepage — the free scan checks for exposed secrets, injection flaws, XSS patterns, missing headers and exposed .env/.git paths, with a copy-paste fix for every finding. No credit card.
The mechanism, in one paragraph
Pickle's format is a tiny stack machine: opcodes can reference any importable class and call it with attacker-chosen arguments. The canonical demonstration — a pickle that runs os.system — fits in two lines. YAML's full Loader does the same through !!python/object tags; PHP's unserialize triggers magic methods across your class graph (gadget chains); Java's readObject built an entire exploit industry. Vibe-Code Audit's detectors flag pickle.loads, yaml.load without a safe loader, unserialize and their cousins across Python, PHP and Java, and the advanced engine adds marshal/dill/cloudpickle and framework-specific variants — because AI models reach for these constantly when asked to 'save this object' or 'load this config'.
Where generated code hides it
The innocent-looking spots: caching model objects in Redis as pickles, 'session data' in a signed-looking cookie, file-upload features that accept .pkl model files or YAML configs, inter-service messages, and ML features that load user-supplied model artefacts (torch.load on a user file is pickle underneath). Any of these becomes RCE the moment the bytes are attacker-influenced — including 'internal' caches that a different, smaller bug lets an attacker write to. That chaining is why 'only our own services produce this data' is a weaker defence than it sounds.
Signatures are not a general answer either: an HMAC over the payload helps only if the key never leaks, the check runs before loading (it must), and every producer signs — a discipline generated code rarely maintains across versions.
What is Unsafe deserialization?
feeding attacker-controlled bytes to a serializer format that can instantiate arbitrary classes or call constructors during loading. The payload executes while being parsed, so validation afterwards is meaningless — the code has already run.
The exit: boring formats, explicit schemas
For data crossing trust boundaries, use JSON with an explicit schema (pydantic, dataclasses, a validator) — JSON builds only strings, numbers, booleans, lists and dicts, so there is nothing to execute. YAML configuration: yaml.safe_load, always, with the same schema discipline. Sessions: keep them server-side or use signed, JSON-encoded tokens with the signature verified before parsing. Model files: prefer safetensors-style formats that contain tensors and metadata only.
Sweep mechanically: grep for loads/load/loads( near pickle, marshal, dill, yaml, unserialize, readObject, torch.load. For each hit, ask one question — can any byte of this input be influenced by someone I do not trust? If the answer is not a confident no, the format changes, not the input source.
If you must keep a legacy path
Sometimes a vendor format pins you. Contain it: verify an HMAC with a dedicated key before deserializing, deserialize in a sandboxed worker with no network and no secrets in its environment, and set a retirement date. Document the exception in the repo so the next AI-assisted edit does not copy the pattern into three new places — patterns in a codebase are prompts for the next generation of code, human or machine.
The ML pipeline variant: model files are pickles
Machine-learning features deserve a specific call-out, because 'load the model' in most tutorials means torch.load — and torch weights files in the classic format are pickle archives, with pickle's full code-execution semantics. An app that lets users upload, share or download community models is a deserialization endpoint wearing a lab coat. The ecosystem's answer is safetensors and similarly inert formats: tensors plus JSON metadata, nothing executable by construction. If your app accepts model files, restrict formats to the inert kind, scan uploads for pickle magic bytes as a backstop, and load anything legacy in the isolated worker described above with no network and no credentials in its environment. The same logic applies to cached inference artefacts and 'precomputed embeddings' shared between teams — any binary format whose loader builds objects deserves the question this guide opened with: who can influence these bytes?
Worked example: ModelShelf, an ML demo host
ModelShelf (fictional) let users upload 'pre-trained models' and loaded them with torch.load — pickle under the hood — for about 140 hosted demos. A scan's unsafe-model-load and pickle detectors fired together. The team verified the exploit in a sandbox with a harmless payload that created a marker file, then rebuilt uploads around the safetensors format with a metadata schema, rejecting pickle-based files outright with a clear error for the 11 users affected. Loading moved into a network-isolated worker as a second layer. Follow-up scans found no pickle-family calls reachable from upload handling.
Your five-action checklist
- Grep for pickle, marshal, dill, cloudpickle, yaml.load without SafeLoader, unserialize, readObject and torch.load across the codebase.
- For each hit, decide who can influence the bytes; any untrusted influence means the format is replaced, not filtered.
- Move cross-boundary data to JSON plus an explicit schema validator; use yaml.safe_load for configuration.
- Keep sessions server-side or as signed JSON tokens, verifying the signature before any parsing.
- Where a legacy format is unavoidable, gate it with HMAC verification and deserialize in an isolated worker with no secrets or network.
Sources
- OWASP Top 10, the OWASP Foundation's standard awareness list of the most critical web application security risks: owasp.org, 2021
- CWE-89: Improper Neutralization of Special Elements used in an SQL Command, MITRE's weakness entry for SQL injection and its mitigations: cwe.mitre.org, 2026
- OWASP Cheat Sheet Series — Secrets Management, OWASP's best-practice guide to storing, rotating and auditing secrets: cheatsheetseries.owasp.org, 2026
Frequently asked questions
We only deserialize data our own app wrote. Is that safe?
Only if no attacker can ever write to that store. The classic chain is a small bug (an open cache endpoint, an upload flaw) plus pickle — the deserializer turns a minor write primitive into code execution. Boring formats remove the multiplier.
Does yaml.safe_load lose features I need?
It loses arbitrary Python objects — which is the point. Dates, nested dicts, lists and scalars all survive. If a config 'needs' python/object tags, that config is code and should be reviewed and shipped as code.
Is signing pickles with HMAC an acceptable fix?
It is a containment, not a fix: it depends on key secrecy and on every load path verifying before parsing, forever. Use it to buy migration time, with the migration actually scheduled.
What about JSON — can it be injected too?
JSON parsers build inert data; the risks move to how you use the data (mass assignment, operator injection), which validation handles. There is no JSON payload that executes during parsing.
Related guides
- JWT alg=none and Key Confusion: How Attackers Forge Any User's Token
- How to Fix CORS Errors Without Opening Your API to Every Website
- Debug Mode in Production: What One Stack Trace Hands an Attacker
- Why AI-Generated Login and API Endpoints Ship Without Rate Limits
- GraphQL Introspection and Batching: The Two Settings AI Starters Leave On
- Prototype Pollution in JavaScript: How One JSON Body Poisons Every Object
- 7 Security Mistakes AI Coders Keep Making
- Supply-Chain Attacks in the AI-Coding Era
- Secret Hygiene: Stop API Key Leaks
- What Code Scanners Can't Find
- Bolt.new Pre-Deploy Security Checklist
- Cursor-Generated Code Review Checklist
Browse the full library on the guides index, run the checks in the launch audit, or compare plans on pricing.
Informational explainer, not a security guarantee. Scan your code free before every deploy.