Demo entry 6064757

pickle

   

Submitted by anonymous on Sep 23, 2016 at 09:37
Language: Python 3. Code size: 732 Bytes.

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()
restricted_loads(pickle.dumps([1, 2, range(15)]))

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).