Full answer
python
import pickle, json
class Exploit:
def __reduce__(self):
return (print, ("code ran during unpickling",))
payload = pickle.dumps(Exploit())
pickle.loads(payload)
data = {"user": "asha", "roles": ["admin"]}
text = json.dumps(data)
print(json.loads(text))
try:
json.loads('{"__reduce__": "os.system"}')["__reduce__"]()
except TypeError as e:
print("JSON gives plain data only:", type(e).__name__)Output:
text
code ran during unpickling
{'user': 'asha', 'roles': ['admin']}
JSON gives plain data only: TypeErrorThe harmless print stands in for something like os.system: simply loading the bytes called it. An attacker who can supply a pickle can therefore run commands with the program's permissions. JSON parsing produces only dicts, lists, strings, numbers, booleans and None, so a string that looks like a function name stays a string. Other risky patterns are eval on input, yaml.load without a safe loader, and subprocess with shell=True and user input. Pickle remains fine for trusted, internal data such as caches written and read by the same service.
python
import pickle, json
class Exploit:
def __reduce__(self):
return (print, ("code ran during unpickling",))
payload = pickle.dumps(Exploit())
pickle.loads(payload)
data = {"user": "asha", "roles": ["admin"]}
text = json.dumps(data)
print(json.loads(text))
try:
json.loads('{"__reduce__": "os.system"}')["__reduce__"]()
except TypeError as e:
print("JSON gives plain data only:", type(e).__name__)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Unpickling can run arbitrary code
- Never unpickle untrusted data
- Use JSON or validated formats
- Sign data with hmac for integrity
- Watch eval, unsafe YAML and shell=True
Common mistakes
- Using pickle for API payloads or cookies
- Assuming obscured pickles are safe
Follow-ups
- How would you safely store Python objects in Redis?
- What does yaml.safe_load prevent?
Tips
- Demonstrate __reduce__