Unsafe deserialization
Quick answer
Unsafe deserialization occurs when a loader interprets untrusted bytes as executable object reconstruction or code. Pickle and related object formats are not safe for untrusted inputs. Use reviewed inert formats, strict contracts and resource limits. Examples use small inert synthetic inputs and standard-library Python. No real endpoints. ByteMind execution is unverified.
Parse inert JSON
import jsonraw = b'{"format":"linear-v1","weights":[2,3]}'model = json.loads(raw)print(model["weights"])Expected output (locally tested): [2, 3]. Parsing produces data; the schema still needs validation.
How it works
Deserialization turns bytes into in-memory values. Python pickle can execute arbitrary code during loading; never load an untrusted pickle, joblib or arbitrary checkpoint. JSON is data rather than executable object reconstruction by default, but large inputs, duplicate keys, unexpected types and unsupported operators still matter. Cap size before parsing, reject unexpected fields, verify signature and digest before model parsing, validate dimensions and numeric ranges, and allow only reviewed operations. Separate the loader from privileged services; do not enable remote custom code. A signed artifact may still be dangerous if its producer is compromised.
Allow only known formats
allowed = {"linear-v1"}formats = ["linear-v1", "opaque", "linear-v2"]print([f in allowed for f in formats])Expected output (locally tested): [True, False, False]. Unknown formats are rejected rather than interpreted.
Common mistakes
A file extension does not establish its contents or safety. Do not use eval, pickle or dynamic imports to parse untrusted input. A valid JSON object is not necessarily a valid model.
Practice and next steps
Design a model contract with two integer coefficients and a format version; reject extra fields. Explain why a valid signature is not a substitute for this check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Unsafe deserialization — knowledge check
Apply unsafe deserialization to small examples and debugging scenarios.
Why reject untrusted pickle?
What is the first size control?
Does JSON guarantee model safety?
How handle unknown operators?
Does a signature imply safe behavior?