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