Sub topic 8
Restricting what an unpickler may import
This chapter assumes you know basic Python classes and special methods, and that you have seen how pickle works as an opcode stream and how __reduce__ can run code on load. Here you will learn how to limit what an unpickler is allowed to import, why that works, and where it stops working.
The problem this solves
A pickle cannot run code on its own. It can only ask the unpickler to import a global (a function or class named by module and name) and then call it. Every dangerous pickle, such as one that calls os.system or builtins.eval, has to name its target first.
That gives a defender a single point of control: the step that resolves a name like os.system into a real Python object. If that step refuses unknown names, the payload fails before anything runs.
Where names get resolved: `find_class`
When the unpickler reads a GLOBAL or STACK_GLOBAL opcode, it calls the method find_class(module, name). The default implementation imports the module and returns the attribute. The REDUCE opcode later calls whatever object was returned.
Because find_class is an ordinary method, you can override it in a subclass of pickle.Unpickler. This is the mechanism the Python documentation recommends for restricting unpickling.
A minimal allowlist unpickler
The following class permits exactly one global, collections.OrderedDict, and rejects everything else.
import io
import pickle
ALLOWED = {("collections", "OrderedDict")}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if (module, name) in ALLOWED:
return super().find_class(module, name)
raise pickle.UnpicklingError(f"blocked global: {module}.{name}")
def safe_loads(data: bytes):
return RestrictedUnpickler(io.BytesIO(data)).load()To see it work, test it with a benign payload and a hostile-looking one. The payload below uses print, so nothing harmful can happen even if the guard fails.
import io
import pickle
from collections import OrderedDict
ALLOWED = {("collections", "OrderedDict")}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if (module, name) in ALLOWED:
return super().find_class(module, name)
raise pickle.UnpicklingError(f"blocked global: {module}.{name}")
def safe_loads(data: bytes):
return RestrictedUnpickler(io.BytesIO(data)).load()
class Payload:
def __reduce__(self):
return (print, ("this should never print",))
good = pickle.dumps(OrderedDict(a=1, b=2))
bad = pickle.dumps(Payload())
print(safe_loads(good))
try:
safe_loads(bad)
except pickle.UnpicklingError as exc:
print("rejected:", exc)The first call prints the OrderedDict. The second prints rejected: blocked global: builtins.print, and the message "this should never print" does not appear. The check happens before REDUCE can call anything.
Allowlist, not blocklist
The guard above lists what is allowed. The alternative is a list of what is forbidden, and it is much weaker. A blocklist such as "reject os.system" has to anticipate every dangerous callable in the standard library and in every installed package. That includes:
subprocess.Popenandsubprocess.runbuiltins.eval,builtins.execandbuiltins.__import__os.popen,os.execvand many otherosfunctionsimportlib.import_module- helpers such as
operator.attrgetterorfunctools.partial, which can be chained to reach a dangerous callable indirectly
A new alias or a third-party function that wraps one of these defeats the blocklist. An allowlist fails closed: anything you did not think of is rejected.
Choosing what to allow
Allow the narrowest set that your data needs, and be exact about it.
- Match on the full
(module, name)pair, not on the module alone. Allowing everything incollectionsis a smaller risk than allowing everything inos, but exact pairs remove the question. - Avoid permitting generic callables. Any entry that can call, import or look up an attribute from an argument (
getattr,eval,__import__,functools.partial) lets an attacker rebuild the capability you meant to deny. - Avoid permitting whole classes whose
__setstate__or constructor performs side effects such as file or network access. The unpickler will invoke them with attacker-chosen arguments. - Keep the allowlist in code that is reviewed, not read from the file being loaded.
A useful habit is to discover the globals first, then decide. The pickletools.genops function walks opcodes without executing anything, so you can list the global references in a sample file.
import pickle
import pickletools
from collections import OrderedDict
def referenced_globals(data: bytes):
found = []
strings = []
for opcode, arg, _pos in pickletools.genops(data):
if opcode.name in ("SHORT_BINUNICODE", "BINUNICODE", "UNICODE"):
strings.append(arg)
elif opcode.name == "GLOBAL":
module, name = arg.split(" ", 1)
found.append((module, name))
elif opcode.name == "STACK_GLOBAL" and len(strings) >= 2:
# Simplified: assumes the two preceding strings are module and name.
found.append((strings[-2], strings[-1]))
return found
data = pickle.dumps(OrderedDict(a=1), protocol=4)
print(referenced_globals(data))This prints [('collections', 'OrderedDict')]. The STACK_GLOBAL handling is a simplification, because strings can also be reused through memo opcodes, so treat this as a way to explore a trusted sample. Do not treat it as a security scanner for untrusted files.
What an allowlist does not protect against
A restricted unpickler narrows the attack surface. It does not make pickle safe in general. Know these limits before relying on it.
Resource exhaustion
The allowlist controls which callables run, not how much work the stream asks for. A small pickle can build deeply nested structures, repeat references, or allocate very large objects, which can consume memory or CPU or exhaust the recursion limit. Restricting imports does nothing about this.
Allowed objects with dangerous behavior
Every allowed global is code that the attacker can call with their own arguments. If you allow a class whose constructor opens files, you have allowed file access. Review each entry as if it were a function exposed to untrusted callers.
Persistent IDs and extensions
The persistent_load hook and the extension registry also influence what gets loaded. The base Unpickler.persistent_load raises an error, but a subclass that implements it, or an application that registers extensions, adds more paths that need review.
The restricted loader must be the only loader
The guard protects only the code path that uses it. If another part of the system calls plain pickle.load or pickle.loads on the same file, the restriction is bypassed. The same applies to libraries that unpickle internally, such as many serialization helpers for caches, queues and model stores.
Pure-Python subclassing caveat
pickle.Unpickler in CPython is implemented in C, and the find_class override is the documented extension point. The pure-Python pickle._Unpickler exists, but you should use the public class. Also remember that find_class is called for every global lookup, including ones made while handling opcodes such as NEWOBJ and for copyreg reconstruction functions, so a real allowlist often needs a few more entries than you expect. Build yours by testing against known-good files.
Connection to weights-only loading
This technique is the idea behind PyTorch's weights_only=True option, which you will meet in the next chapters. PyTorch checkpoints are pickles, and they legitimately need to reference tensor reconstruction helpers and containers such as OrderedDict. A restricted unpickler lets a loader permit those specific names and reject the rest. Writing your own allowlist for tensor files is not a good idea in practice, because a maintained implementation in the framework tracks the exact set of internals that change between versions. The lesson here is the mechanism, so you can reason about what that option does and does not guarantee.
Summary of the approach
| Question | Answer |
|---|---|
| Which method do I override? | `find_class(self, module, name)` on `pickle.Unpickler` |
| Allowlist or blocklist? | Allowlist, matched on exact `(module, name)` pairs |
| What happens on a rejected name? | Raise `pickle.UnpicklingError` so loading stops |
| Does it stop memory or CPU abuse? | No |
| Does it protect other code that calls `pickle.load`? | No, only the code path that uses the restricted class |
Exercise
A teammate proposes a restricted unpickler that raises an error for the names os.system, subprocess.Popen and builtins.eval, and allows everything else. Explain why this design is unsafe and describe the safer design, including which method you override and what it should do for names it does not recognize.
Show answer
This is a blocklist, and it only stops the dangerous callables someone remembered. Attackers can use others, such as builtins.exec, os.popen, importlib.import_module, or helpers like functools.partial combined with another callable, and new or third-party functions also slip through. The safer design is an allowlist. Subclass pickle.Unpickler and override find_class(self, module, name). If (module, name) is in a small, reviewed set of exact pairs, return super().find_class(module, name). For every other name, raise pickle.UnpicklingError so loading stops before REDUCE can call anything.
Exercise
You have added a restricted unpickler to your model-loading function, and a test shows it rejects a print payload. Name two reasons a file could still cause harm or a failure on your system.
Show answer
First, the restriction controls only which globals can be called, so a crafted stream can still exhaust memory or CPU through huge or deeply nested objects. Second, any allowed global is callable with attacker-chosen arguments, so an allowed class or function with side effects can be abused. A further valid reason is that another code path, such as a library that calls plain pickle.load on the same file, bypasses the restriction entirely.