← Back to Python, page 4

python-0070 · Hard senior

Why is pickle unsafe for untrusted data, and what should be used instead?

Unpickling can execute arbitrary code, because a pickle can instruct the loader to call any importable function with chosen arguments through __reduce__. Never unpickle data from users, networks or shared storage you do not fully control. Use JSON or another data-only format with validation, and sign data with hmac if integrity matters.

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: TypeError

The 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__