Python Deserialization

Lecture

Insecure Deserialization Attack Explained - PwnFunction

pickle

Use pickle.dumps for serialization and pickle.loads for deserialization:

__reduce__()

Motivation: Whenever you try to pickle an object, there will be some properties that may not serialize well. For instance, an open file handle. In this case, pickle won't know how to handle the object and will throw an error.

Solution: To overcome this barrier, pickle implemented the __reduce()__ method. __reduce__() is a special method that is referenced when we are serializing data. The reduce function essentially tells the pickle library how to serialize the object. Then, when we are unserializing the data, this information is used to rebuild the object.

The following code will generate a payload that executes id:

Attack Scenario

Suppose there is a Windows server running a web app that serializes user cookie using pickle. The following code will generate a cookie that executes the reverse shell payload:

Lab: Vulhub Python unpickle Deserialization

Setup

Python unpickle Deserialization - Vulhub

Code Review

The cookie user is deserialized by pickle.loads(). Since the cookie is a type of user-controlled data, this Flask web app is vulnerable to Python unpickle deserialization attack.

Solution

We are going to create a malicious object containing the reverse shell payload and send it to the server. On the server side, the Flask web app will deserializes the malicious payload and execute it:

Exploit

Note that Docker IP (our netcat listener's IP) is 172.17.0.1 by default and the Flask IP is either 172.19.0.1 or 127.0.0.1, both work.

Takeaway

Do NOT deserialize user-provided data, such as cookies, URL parameters, and etc.

Last updated

Was this helpful?