python序列化

2024-09-09 22:59:00
admin
原创 61
摘要:python序列化

一、python序列化

1、python序列化使用内置的pickle,对象可以序列化为字节或文件;

2、仅仅序列化json数据,或者限制反序列化类型,避免反序列化漏洞;


序列化示例:

data = {'name':'Alice', 'age':25, 'city':'New York'}
#dump to json
data_json = json.dumps(data)
data = json.loads(data_json)
#dump to byte
data_bytes = pickle.dumps(data)
data = pickle.loads(data_bytes)
#dump to file
with open('data.pickle', 'wb') as file:
    pickle.dump(data, file)
with open('data.pickle', 'rb') as file:
    data = pickle.load(file)


解析序列化数据:

data = {'name':'Alice', 'age':25, 'city':'New York'}
data_bytes = pickle.dumps(data)
data = pickle.loads(data_bytes)
pickletools.dis(data_bytes)


恶意反序列化:

class Malicious:
    def __reduce__(self):
        return (os.system, ('ls -al',))
malicious_data = pickle.dumps(Malicious())
pickle.loads(malicious_data)


反序列化类型限制:

permitTypes = {"str", "list", "dict", "set", "int", "float", "bool"}
class RestrictedUnpickler(pickle.Unpickler):
    def find_class(self, module, name):
        if module == "builtins" and name in permitTypes:
            return pickle.Unpickler.find_class(self, module, name)
        raise pickle.UnpicklingError(f"global {module}.{name} is forbidden")
def restricted_loads(s):
    return RestrictedUnpickler(io.BytesIO(s)).load()

发表评论
评论通过审核之后才会显示。