Security Issues with Python Pickle

Ever wonder about the warning found near the top of the Pickle documentation page?

Warning on Python Pickle documentation page

I used to work with Pickled objects quite a bit; almost all of my Python projects contained heavy Pickle use. However, looking back through the documentation, I noticed the warning at the top of the page and decided to do a little searching.

Turns out, the security implications of unpickling a nasty string could be quite disastrous. I won’t go into much detail here as this article by Nadia Alramli is an excellent overview. In short, arbitrary system calls can be executed during unpickling. The article concludes with an excellent workaround to create a safer unpickling class which I have reposted below for reference.

import sys
import pickle
import StringIO

class SafeUnpickler(pickle.Unpickler):
    PICKLE_SAFE = {
        'copy_reg': set(['_reconstructor']),
        '__builtin__': set(['object'])
    }
    def find_class(self, module, name):
        if not module in self.PICKLE_SAFE:
            raise pickle.UnpicklingError(
                'Attempting to unpickle unsafe module %s' % module
            )
        __import__(module)
        mod = sys.modules[module]
        if not name in self.PICKLE_SAFE[module]:
            raise pickle.UnpicklingError(
                'Attempting to unpickle unsafe class %s' % name
            )
        klass = getattr(mod, name)
        return klass

    @classmethod
    def loads(cls, pickle_string):
        return cls(StringIO.StringIO(pickle_string)).load()

Please check out Nadia’s article for more information. Her site also contains some other great python tips and tricks, many of which involve dealing with Python Image Library.