跳到内容

suspicious-marshal-usage (S302)

源自 flake8-bandit linter。

作用

检查对 marshal 函数的调用。

为什么这不好?

使用 marshal 反序列化不受信任的数据是不安全的,因为它允许创建任意对象,这些对象可用于实现任意代码执行和其他意外行为。

避免使用 marshal 反序列化不受信任的数据。相反,考虑更安全的格式,例如 JSON。

如果必须使用 marshal 反序列化不受信任的数据,请考虑使用密钥对数据进行签名,并在反序列化有效负载之前验证签名。这将防止攻击者将任意对象注入序列化数据中。

预览版中,此规则还会标记对 marshal 函数的引用。

示例

import marshal

with open("foo.marshal", "rb") as file:
    foo = marshal.load(file)

建议改为

import json

with open("foo.json", "rb") as file:
    foo = json.load(file)

参考