Lesson · Security & Robustness Essentials
Serialization Safety
55 min readSerialization Safety
Deserialization is a trust boundary because some formats can construct powerful runtime objects. JSON is data-oriented; pickle is executable enough that untrusted pickle data must never be loaded.
Learning goals
- Explain how
pickle.loadscan execute code while reconstructing an object, through hooks such as__reduce__. - Decide whether a payload is trusted by asking who can shape the bytes, not by how ordinary the bytes look.
- Parse text with
json.loads, name the small set of value types it produces, and read thejson.JSONDecodeErrorwhen the grammar fails. - Describe a deserialization boundary in your own code and choose a format whose worst case is a parse error rather than object construction.
- Show what a JSON round trip does to a tuple (
(1, 2)becomes a list) and contrast it with the same round trip through pickle.
Mental model
The decision order matters: trust determines the format, not the other way around. Pickle is a Python-to-Python transport for bytes you produced, while JSON is the default for anything an outside party can shape, because its worst failure is a parse error. Crossing the boundary ends the easy part: whatever comes out still needs a shape check before the program relies on it.
Mental model
read it top to bottom
bytes arrive at a deserialization boundary ↓ who can shape these bytes? your own process: pickle may be acceptable ↓ anyone outside: data-only format json.loads(text) -> dict, list, str, int, float, bool, None ↓ then validate the structure before use
Core idea
Every format hides an answer to one question: what can loading these bytes do besides produce data? Pickle's answer includes object construction and function calls, which is why it belongs to a single-process round trip and nothing further. JSON's answer is limited to building dicts, lists, strings, numbers, booleans, and None, which makes it the defensible default at a boundary, with validation as the follow-up step.
Pickle risks
pickle reconstructs Python objects from a byte stream, and the format can name classes and call functions through hooks such as __reduce__, so loading bytes an attacker shaped can execute code as a side effect of pickle.loads. The danger is not limited to unusual classes: any importable name reachable from the stream becomes an object-construction request. Treat pickle as a Python-to-Python transport for data your own process produced, and choose a data-only format for anything that crossed a trust boundary.
Trusted vs untrusted input
Trusted input is data your own process produced, or data that arrived over a channel you control end to end; that is the only condition under which loading pickle bytes is acceptable. Untrusted input is anything an outside party can shape, including uploaded files, request bodies, and messages from other services, and it belongs in a data-only format such as JSON. The distinction is about who can influence the bytes, not about how ordinary the bytes look.
JSON as a data format
JSON is a text format that represents only data: objects, arrays, strings, numbers, booleans, and null, with no way to name a class or call a function during parsing. json.loads turns the text into dict, list, str, int, float, bool, and None values, and raises json.JSONDecodeError when the text does not follow the grammar. That data-only restriction is exactly why JSON is safe at a boundary: the input has no mechanism to become behavior, even when the payload is valid JSON of the wrong shape or size.
Deserialization boundaries
A deserialization boundary is the point where stored or transmitted bytes become live Python objects again, and everything beyond it inherits the trust level of whoever shaped those bytes. The format decides what the bytes can turn into: JSON yields plain data, while pickle can request object construction and function calls. Cross the boundary with a format whose worst case is a parse error, then validate the resulting structure before the rest of the program uses it.
Walkthrough
json.dumps(trusted)turns the dict into text,'{"name": "Ada"}', losing nothing here because a dict of strings maps cleanly onto a JSON object.json.loads(safe_text)parses that text back into a dict, and the whole round trip is data-only at both ends: no class is named and no function runs.pickle.dumps(trusted)produces bytes rather than text, andpickle.loads(blob)rebuilds the dict from them. The printed result is identical to the JSON line, which is exactly the trap: the same visible output can come from a loader that executed reconstruction logic to get there.- The comment states the rule the code alone cannot demonstrate: pickle is for trusted Python-to-Python data only, so the success of this example says nothing about loading bytes that arrived from someone else.
- Predict before running: whether
safe_textis astrorbytes, whetherblobis astrorbytes, and whether the twoprintcalls show any difference in output.
Experiments to try
- Print
type(safe_text)andtype(blob), confirm one isstrand the otherbytes, then feedblobtojson.loadsand record the exception. - Round-trip
(1, 2)and{"a", "b"}through both formats: record which value JSON refuses with aTypeErrorand which one changes type silently on the JSON round trip. - Define a class whose
__reduce__returns(print, ("executed during load",)), dump an instance withpickle.dumps, then load it and observe that the call happens insidepickle.loads. - Feed
'{"name": "Ada",}'tojson.loadsand read theJSONDecodeErrormessage and position; then catch it and returnNoneto see what a silent fallback hides from the caller.
Common mistakes
- Loading a pickle that arrived from an upload, a request body, or a queue because "it is just a dict": the loader cannot know the payload is a dict until it has already honored whatever the stream requested, so the harmless case is indistinguishable from the malicious one.
- Treating
json.dumpsandpickle.dumpsas interchangeable storage formats: JSON covers a fixed, small type set and changes some types (a tuple comes back as a list), while pickle preserves Python objects, so a round trip through the wrong format silently changes values or fails with aTypeError. - Taking a successful parse as validation:
json.loadsreturning a dict proves the text followed the JSON grammar, not that the fields exist, have the right types, or hold acceptable values, so indexing straight into the result fails later with aKeyErroror works on the wrong type. - Trusting pickle because the channel is "internal" or the bytes carry a signature: that argument rests on the channel or the signer never being compromised, and the safer move is a format that cannot execute anything even if it is.
Practice: Easy
- Run the worked example and print
type(safe_text)andtype(blob); then passblobtojson.loadsand record the exact exception class and message. - Round-trip
(1, 2)and{"a", "b"}throughjson.dumps/json.loadsand throughpickle.dumps/pickle.loads; record which type changes on the JSON side and which value raisesTypeError. - Call
json.loads('{"name": "Ada",}'), read theJSONDecodeError, then catch it and returnNone; state in one sentence what the caller can no longer distinguish.
Practice: Medium
- Write
parse_config(text)that runsjson.loadsinsidetry/except, raisesValueError("config must be a JSON object")when the parsed value is not a dict, and returns the dict otherwise; test with a valid object, non-JSON text, and a JSON array. - Replace a
pickle.load(open(path, "rb"))call in a small script withjson.loadover a text file, keeping the data shape unchanged for a dict of strings and numbers; note what had to change on the write side and what pickle preserved that JSON could not. - Take the
__reduce__demonstration and write two or three sentences for a reviewer explaining what an attacker gains from controlling pickle bytes and which alternative format removes that capability.
Practice: Hard
- Build a small job-input gate: a function that receives bytes, refuses to pickle-load anything not marked internal, parses external payloads with
json.loads, validates required keys and their types, and returns a validated dict; add tests for a valid job, malformed JSON, a missing key, and a wrong type. - Build a pickle hazard lab: define a class whose
__reduce__records a message when called, pickle an instance, load it in a fresh process, and write up the exact moment the code ran; then move the same payload to JSON and show the format cannot express the call. - Write a format-choice review for three channels (your own cache file, a user upload, a message from another service): for each, name the allowed format, the worst case if the input is hostile, and the validation that runs after parsing; defend the one channel where you chose pickle.
Lesson checklist
- I can explain how
pickle.loadscan run code while rebuilding an object. - I can decide whether a payload is trusted by asking who can shape its bytes.
- I can parse text with
json.loads, name what it can produce, and handle its parse error. - I can point at a deserialization boundary in a program and justify the format chosen for it.
Remember
Serialization safety is a format question with a trust answer: pickle reconstructs Python objects and can execute code on the way, so it stays inside data your own process produced, while JSON builds only plain data and raises a parse error as its worst case. Pick the format from the channel's trust level, then validate the structure you actually need after parsing.
Interview angles
What is the main purpose of **Pickle risks**?+
pickle.loads rebuilds Python objects from bytes and can name classes and call functions while doing it, so loading a stream an attacker shaped is equivalent to running code they chose. Pickle is acceptable only as a Python-to-Python transport for data your own process produced.
What should you pay attention to when using **Trusted vs untrusted input**?+
Trust is about who can shape the bytes, not how ordinary they look: your own process's output can be trusted, while uploads, request bodies, and messages from other services must be parsed with a data-only format such as JSON.
How does **JSON as a data format** fit into this lesson?+
JSON can build only plain data (objects, arrays, strings, numbers, booleans, null) and has no way to name classes or call functions, and json.loads raises json.JSONDecodeError for text outside the grammar. That restriction is what lets it cross a trust boundary where pickle cannot.
What does a successful `json.loads` call prove, and what does it not prove?+
It proves the text followed the JSON grammar and produced plain data. It does not prove the fields exist, carry the expected types, or hold acceptable values, so the structure still needs validation before the program relies on it.