Unsafe Object Deserialization
Watch a harmless event happen during object reconstruction before validation, then replace the import with bounded data and a schema.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
A layout importer reads an uploaded file and checks the result's dimensions. The dimensions are wrong, so the app rejects the layout. Could something already have happened before that rejection?
With some object formats, reconstruction can invoke behavior while producing the object. Deserialization means rebuilding values or objects from a saved representation. The important difference here is whether reading the bytes only produces data or can also run behavior.
We'll watch a harmless marker appear during reconstruction, before validation. Then we'll replace the object format with bounded data and a visible schema. Other formats and signed producers come later, once the ordering is clear.
Demonstrate the ordering with a harmless local marker
You do not need an operating-system command to understand the mechanism. The following self-contained teaching example records an event in a local list while an object is reconstructed. It deliberately performs no network request, file write, or process execution. It illustrates decoder capability and ordering, not a payload to send to another service.
import pickle
events = []
def reconstruction_marker(label):
events.append(label)
return {"width": "not-an-integer", "height": 100, "cells": []}
class ExportedLayout:
def __reduce__(self):
return (reconstruction_marker, ("reconstruction ran",))
def validate_layout_header(value):
if not isinstance(value, dict):
raise ValueError("layout must be an object")
if type(value.get("width")) is not int:
raise ValueError("width must be an integer")
return value
serialized = pickle.dumps(ExportedLayout())
assert events == []
try:
candidate = pickle.loads(serialized)
validate_layout_header(candidate)
except ValueError:
pass
assert events == ["reconstruction ran"]
The validation fails as intended because width is not an integer. The event still exists. This is why a check on the returned type, an exception handler around the import, or a rejected final response cannot establish that no decoder behavior occurred.
The exact behavior an attacker can invoke depends on the format, available modules and classes, decoder restrictions, runtime version, and process authority. The demonstration establishes that reconstruction is not a passive conversion into a dictionary. The Python documentation explicitly warns that malicious pickle data can execute code during unpickling.
In a real review, use an isolated training fixture and a harmless marker appropriate to that fixture. Do not verify the finding by executing destructive commands or accessing unrelated data. Record the point at which the marker appears relative to validation so the evidence supports the actual root cause.