如果解压对像中有重构的reduce操作, pickle.loads时会执行reduce方法中的内容.
比如:
import io import os import pickle class BadCode(object): def __reduce__(self): return (os.system, ('echo fuckyou!',)) bc = BadCode() bbb = pickle.dumps(bc) pickle.loads(bbb)
限制方法, 重载一下Unpicke方法, 只解压特定类型的对像.
class RestrictedUnpickler(pickle.Unpickler): def find_class(self, module, name): print(module, name) if module == "builtins" and name in {"str", "list", "dict", "set", "int", "float", "bool"}: return getattr(__import__(module), name) raise pickle.UnpicklingError(f"global '{module}.{name}' is forbidden") def load_reduce(self): # 禁止使用 reduce raise pickle.UnpicklingError("reduce() is not allowed") def restricted_loads(s): return RestrictedUnpickler(io.BytesIO(s)).load() ok = restricted_loads(bbb) print('ok: ',ok)
本文作者:JiangOil
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!