Principle:Trailofbits Fickling Pickle to AST Conversion
| Knowledge Sources | |
|---|---|
| Domains | Security, Reverse_Engineering, Static_Analysis |
| Last Updated | 2026-02-14 14:00 GMT |
Overview
A decompilation technique that converts pickle VM opcodes into an equivalent Python abstract syntax tree, enabling human-readable code recovery and AST-based security analysis.
Description
Pickle to AST Conversion simulates the pickle virtual machine symbolically rather than executing it. The pickle VM is a stack machine with operations for pushing constants, calling functions, storing to a memo dictionary, and building data structures. Instead of executing these operations on real Python objects, the Interpreter translates each opcode into an equivalent Python AST node.
The result is an ast.Module that represents the equivalent Python source code — the code that would produce the same result as deserializing the pickle. This AST can then be:
- Unparsed back to readable Python via ast.unparse()
- Walked by analysis passes to detect dangerous patterns (imports, calls to exec/eval)
- Inspected to identify unused variables, suspicious imports, and data exfiltration
Usage
Use this principle when you need to understand what a pickle file does, either for human review (decompilation) or automated analysis (AST walking). It is the core enabling technique for both safety analysis and forensic investigation.
Theoretical Basis
The pickle VM has a stack and a memo dictionary. The Interpreter maintains symbolic equivalents:
# Pseudocode: Symbolic interpretation
stack: list[ast.expr] = [] # Symbolic stack
memory: dict[int, ast.expr] = {} # Symbolic memo
module_body: list[ast.stmt] = [] # Generated statements
for opcode in opcodes:
if opcode is GLOBAL(module, name):
stack.push(ast.ImportFrom(module, name))
elif opcode is REDUCE:
args = stack.pop() # tuple of arguments
func = stack.pop() # callable
stack.push(ast.Call(func, args))
elif opcode is STOP:
module_body.append(ast.Assign("result", stack.pop()))
The final AST represents the complete deserialization logic as standard Python, with imports, variable assignments, function calls, and the final result assignment.