pickle security

Geoffrey Talvola gtalvola at nameconnector.com
Fri Feb 1 14:26:11 EST 2002


I'm trying to understand how to safely unpickle untrusted strings.  I'll
summarize what I think I've learned from Google searches, and someone tell
me if I'm wrong.

If you want to unpickle a string s but you only want built-in types to be
created during the unpickling process, never classes or extension types,
here's the best way to do it:

import cPickle, cStringIO
unpickler = cPickle.Unpickler(cStringIO.StringIO(s))
unpickler.find_global = None
result = unpickler.load()

And if you want to allow particular classes to be unpickled, for example if
you want to allow the class "bar" in the module "foo" to be unpickled, you
can use something like:

import cPickle, cStringIO
def find_global(module, klass):
    if module == 'foo' and klass == 'bar':
        import foo
        return foo.bar
    else:
        raise cPickle.UnpicklingError, \
              "can't unpickle a %s.%s" % (module, klass)
unpickler = cPickle.Unpickler(cStringIO.StringIO(s))
unpickler.find_global = find_global
result = unpickler.load()

Did I get it right?  Are there any other security issues I need to be aware
of, or does this cover them?

-- 

- Geoff Talvola
  gtalvola at NameConnector.com




More information about the Python-list mailing list