正如我们所知,pickle默认是不安全的,因为pickle.load可以在用户的机器上执行任意代码,但是有一种方法可以将它限制在一些安全的#34;类型,如下所述: 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()
但是,文档说得相当模糊:
pickle模块对于错误或恶意构造的数据是不安全的。切勿取消从不受信任或未经身份验证的来源收到的数据。
这种限制真的很安全吗?或者还有一些其他方法可以通过传递" bad"来执行任意代码。输入到pickle.load?