3

As we know, pickle is insecure by default because pickle.load can execute arbitrary code on user's machine, but there's a way to restrict it to some "safe" types, as described here: https://docs.python.org/3.4/library/pickle.html#restricting-globals

import builtins
import io
import pickle

safe_builtins = {
    'range',
    'complex',
    'set',
    'frozenset',
    'slice',
}

class RestrictedUnpickler(pickle.Unpickler):

    def find_class(self, module, name):
        # Only allow safe classes from builtins.
        if module == "builtins" and name in safe_builtins:
            return getattr(builtins, name)
        # Forbid everything else.
        raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
                                     (module, name))

def restricted_loads(s):
    """Helper function analogous to pickle.loads()."""
    return RestrictedUnpickler(io.BytesIO(s)).load()

However, the documentation speaks rather vaguely about that:

The pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.

Is it really safe with this restriction? Or there are still some other ways to execute arbitrary code by passing "bad" input to pickle.load?

Display Name
  • 8,022
  • 3
  • 31
  • 66

0 Answers0