Sub topic 4
Reading a pickle with pickletools
This chapter assumes you know basic Python and have read the earlier chapters on the pickle opcode stream and on __reduce__. You should know that a pickle is a list of opcodes that a small virtual machine runs, and that GLOBAL-style opcodes plus REDUCE can call functions. Here you will learn to read that opcode list without running it.
Why inspect instead of load
The only safe way to learn what a pickle does is to read its opcodes. Calling pickle.loads runs them, so a malicious file has already acted by the time it returns. The standard library module pickletools decodes the byte stream into opcodes and arguments. It does not execute them and does not import anything.
Disassembling with pickletools.dis
pickletools.dis prints one line per opcode: the byte offset, the opcode's raw byte, its name, and its argument. The example below pickles the Payload class from the previous chapter and disassembles the result. Protocol 4 is set explicitly so the output looks the same across Python versions.
import pickle
import pickletools
class Payload:
def __reduce__(self):
return (print, ("hello",))
data = pickle.dumps(Payload(), protocol=4)
pickletools.dis(data) # decodes the opcodes without executing themOutput (offsets and the frame length may differ slightly):
0: \x80 PROTO 4
2: \x95 FRAME ...
11: \x8c SHORT_BINUNICODE 'builtins'
21: \x94 MEMOIZE (as 0)
22: \x8c SHORT_BINUNICODE 'print'
29: \x94 MEMOIZE (as 1)
30: \x93 STACK_GLOBAL
31: \x94 MEMOIZE (as 2)
32: \x8c SHORT_BINUNICODE 'hello'
39: \x94 MEMOIZE (as 3)
40: \x85 TUPLE1
41: \x94 MEMOIZE (as 4)
42: R REDUCE
43: \x94 MEMOIZE (as 5)
44: . STOPRead it as a stack program:
SHORT_BINUNICODE 'builtins'andSHORT_BINUNICODE 'print'push two strings.STACK_GLOBALpops those two strings and pushes the objectbuiltins.print. This is the import.SHORT_BINUNICODE 'hello'andTUPLE1build the argument tuple("hello",).REDUCEpops the tuple and the callable and callsprint("hello"). This is the call.STOPends the program and returns the top of the stack.
The pattern to remember is a global lookup followed later by REDUCE. MEMOIZE lines only store values for reuse and carry no risk.
You can run the same decoder from a shell on a file. Add -a for a short description of each opcode.
python -m pickletools -a suspicious.pklWhich opcodes matter for security
Most opcodes build plain data: numbers, strings, lists, dicts and tuples. A small set can reach into the Python runtime.
| Opcode | What it does | Why it matters |
|---|---|---|
| `GLOBAL` | Imports `module name` given as a text line (protocols 0 to 3) | Names any importable object |
| `STACK_GLOBAL` | Imports using two strings from the stack (protocol 4+) | Same, but the names are not next to the opcode |
| `INST`, `OBJ` | Create an object from a class (older protocols) | Calls a class with arguments |
| `REDUCE` | Calls the callable below the argument tuple | Performs the actual call |
| `NEWOBJ`, `NEWOBJ_EX` | Calls `cls.__new__` | Creates instances of the named class |
| `BUILD` | Updates an object's state, usually `__dict__` | Common in normal pickles, and it can call `__setstate__` |
BUILD is routine in real checkpoints, so flagging it alone only produces noise. The useful signal is the list of globals, because it shows every name the file wants to import.
Writing a scanner with genops
pickletools.genops yields (opcode, argument, position) tuples instead of printing text. That lets you filter programmatically. The scanner below lists every global. For GLOBAL, the argument is already the string "module name". For STACK_GLOBAL, the scanner takes the two most recent string arguments it has seen.
import pickle
import pickletools
STRING_OPS = {"SHORT_BINUNICODE", "BINUNICODE", "BINUNICODE8", "UNICODE"}
CALL_OPS = {"REDUCE", "INST", "OBJ"}
def scan(data: bytes):
"""Return (globals, call_count) found in a pickle without loading it."""
strings = []
found = []
calls = 0
for op, arg, pos in pickletools.genops(data):
if op.name in STRING_OPS:
strings.append(arg)
elif op.name == "GLOBAL":
found.append((pos, arg))
elif op.name == "STACK_GLOBAL":
if len(strings) >= 2:
found.append((pos, f"{strings[-2]} {strings[-1]}"))
else:
found.append((pos, "<unresolved>"))
elif op.name in CALL_OPS:
calls += 1
return found, calls
class Payload:
def __reduce__(self):
return (print, ("hello",))
benign = pickle.dumps({"lr": 0.1, "layers": [64, 32]}, protocol=4)
hostile = pickle.dumps(Payload(), protocol=4)
print(scan(benign)) # ([], 0): plain data, no imports, no calls
print(scan(hostile)) # ([(30, 'builtins print')], 1): imports print and calls itThe benign pickle has no globals and no calls. The hostile one imports builtins print and performs one call.
Limits of static inspection
A scanner like this is a review aid, not a guarantee. Keep these gotchas in mind:
- Memoized strings. If the module name was stored earlier and fetched with
BINGETorLONG_BINGET, it is not among the most recent strings. The scanner above would then report the wrong name or<unresolved>. Treat<unresolved>as a failure, not as a pass. - Chained calls. One
REDUCEcan return an object that a laterREDUCEcalls. Counting globals shows what is imported, but not every route to a dangerous function. Allowinggetattr-style globals orbuiltinsentries usually makes a file unsafe. - Allowed does not mean harmless. Some functions in common libraries can run commands or read files. Judge each global by what it can do, not by whether the module sounds familiar.
- Hidden second pickle. A file may hold other pickles in extra archive members, or data that a later step unpickles again.
For these reasons, inspection pairs with an allowlist at load time, which later chapters cover. Inspection tells you what a file asks for. The allowlist enforces what it may get.
Inspecting a PyTorch checkpoint
A modern .pt or .pth file saved by torch.save is a zip archive. The pickle sits inside it as a member named data.pkl under a top-level folder. The large tensor bytes are stored in separate members, so the pickle itself stays small. You can read it without importing PyTorch:
import zipfile
import pickletools
def dis_checkpoint(path: str):
with zipfile.ZipFile(path) as zf:
names = [n for n in zf.namelist() if n.endswith("data.pkl")]
if not names:
raise ValueError("no data.pkl found; this may be a legacy or non-zip file")
pickletools.dis(zf.read(names[0]))
dis_checkpoint("model.pth")A clean state dict typically lists globals such as collections OrderedDict and torch._utils _rebuild_tensor_v2, plus storage types like torch FloatStorage. Anything that reaches os, subprocess, builtins, posix or socket is a red flag. Files saved with very old PyTorch versions are not zip archives. dis_checkpoint raises an error for them instead of guessing.
Practical review habits
- Decode first, load later, and only load if every global is accounted for.
- Save the list of globals next to the file, so a later change in a re-uploaded file is easy to spot.
- Prefer formats that have no opcode stream at all when you have a choice. The following chapters cover them.
Exercise
You run pickletools.dis on a downloaded pickle and see SHORT_BINUNICODE 'os', SHORT_BINUNICODE 'system', STACK_GLOBAL, a string argument, TUPLE1, then REDUCE. What will happen if you call pickle.loads on it, and which two opcodes tell you so?
Show answer
Loading will import os.system and call it with the string argument, so it runs a shell command. STACK_GLOBAL (which resolves to os system) shows the import, and REDUCE shows the call.
Exercise
Why does the scan function report <unresolved> for some protocol 4 pickles, and how should you treat that result?
Show answer
STACK_GLOBAL takes its module and name from strings on the stack. If those strings were stored earlier and re-fetched with a memo opcode such as BINGET, they are not the two most recent string arguments, so the simple scanner cannot resolve them. Treat <unresolved> as unsafe until you check the file by hand with pickletools.dis or a scanner that tracks the memo.