Python pickle解压时可能存在安全风险
Python pickle解压时可能存在安全风险
如果解压对像中有重构的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)
人工智障与神经病网络
https://www.cnblogs.com/JiangOil/