Sub topic 8
Restricting What an Unpickler May Import
Assume you know basic Python classes, special methods, and PyTorch checkpoints. You should also know that a pickle file is a byte stream that can describe Python objects. This chapter focuses on one defense: allowing an unpickler to resolve only explicitly approved classes and functions.
Why imports matter during unpickling
Pickle does not store every class definition inside the file. Instead, it can store a reference such as:
- Module:
collections - Name:
OrderedDict
During loading, the unpickler imports that object and reconstructs it. This lookup is called resolving a global. A pickle can request many importable callables, including functions that perform unwanted actions.
The find_class method controls these lookups. A restricted unpickler overrides that method and checks every requested (module, name) pair against an allowlist.
import io
import pickle
class Payload:
def __reduce__(self):
# This requests print(...) during ordinary unpickling.
return (print, ("code ran during loading",))
class RestrictedUnpickler(pickle.Unpickler):
ALLOWED = {
("collections", "OrderedDict"),
}
def find_class(self, module, name):
if (module, name) in self.ALLOWED:
return super().find_class(module, name)
raise pickle.UnpicklingError(
f"blocked global: {module}.{name}"
)
def restricted_loads(data):
return RestrictedUnpickler(io.BytesIO(data)).load()
data = pickle.dumps(Payload())
try:
restricted_loads(data)
except pickle.UnpicklingError as error:
print(error)The payload contains a reference to builtins.print. Because that pair is not in ALLOWED, loading raises UnpicklingError before print is called.
How the allowlist works
The unpickler still interprets pickle opcodes. The override only changes how global references are resolved. A permitted reference continues through the normal implementation:
return super().find_class(module, name)Every other reference is rejected. This is safer than allowing a broad module such as builtins, because a broad rule may permit dangerous functions or classes.
Common errors and limits
- Allowing a whole module:
if module == "collections"is broader than necessary. Approve exact pairs. - Allowing every requested class: This removes the protection.
- Assuming this validates tensor data: The method controls global lookup, not tensor sizes, memory use, or malformed input.
- Using it as a complete sandbox: Other pickle operations and implementation details can create additional risk. Prefer a format that does not contain executable reconstruction instructions.
- Forgetting compatibility: Legitimate checkpoints may reference classes that are absent from the allowlist. Rejection is safer than adding entries automatically.
> callout warning > An allowlist is a narrow compatibility mechanism, not proof that a pickle is trustworthy. Load untrusted files in an isolated process with limited permissions, and prefer data-only formats when possible. >
When to use this defense
Use a restricted unpickler only when you must read a pickle-based artifact and you understand the objects it should contain. For PyTorch files, prefer torch.load(..., weights_only=True) when the checkpoint is compatible. That option applies a framework-maintained restriction intended for tensor weights and simple containers.
Exercise
Why should an allowlist contain exact (module, name) pairs instead of only module names?
Show answer
Exact pairs limit the loader to the specific classes or functions required by the artifact. Allowing an entire module may expose additional callable objects that can perform unwanted actions.