Reject Unsafe Deserialization Formats
Core idea
Deserialization reconstructs values from stored or transmitted bytes. pickle can invoke code during loading and must not be used for untrusted or tampered data. shelve and multiprocessing connections can also involve pickle. For external records prefer a constrained data format, authenticate the source when required, bound the size and validate the decoded schema. JSON is not automatically resource-safe or authorized.
import jsonraw = b'{"label":"box","count":2}'if len(raw) > 128: raise ValueError('too large')row = json.loads(raw)if (not isinstance(row, dict) or set(row) != {'label','count'} or type(row['count']) is not int or not 0 <= row['count'] <= 100 or not isinstance(row['label'], str) or not 1 <= len(row['label']) <= 20): raise ValueError('invalid row')print(row['label'], row['count'])A bounded data record is decoded and checked for required fields and types.
Expected output:
box 2Refuse unsupported formats before parsing
import jsondef decode(raw, media): if media != 'application/json': raise ValueError('unsupported format') if len(raw) > 128: raise ValueError('too large') return json.loads(raw)try: decode(b'not loaded', 'application/x-pickle')except ValueError as exc: print(exc)The dispatcher rejects pickle without invoking any pickle loader. Decoded JSON still requires schema validation.
Expected output:
unsupported formatCommon mistake
Never unpickle unknown bytes to see what they contain. A content-type label is not proof of trust; malformed or mislabeled data must still fail parsing and validation.
Practice
Write a test that rejects unsupported media types before the decoder runs. Add oversized JSON and invalid-schema cases. Do not create or load executable serialization payloads.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Unsafe deserialization
Check your understanding of unsafe deserialization.
What is printed?
import jsonprint(json.loads("null") is None)What is printed?
print(len(b"data") <= 3)What should happen to an untrusted pickle?
Does JSON parsing alone establish a valid domain record?