suspicious-url-open-usage (S310)
源自 flake8-bandit linter。
作用
检查 URL 打开函数使用非预期协议的情况。
为什么这不好?
一些 URL 打开函数允许使用 file:
或自定义协议(代替 http:
或 https:
)。攻击者可能能够使用这些协议访问或修改未经授权的资源,并导致意外行为。
为了降低这种风险,请审核所有 URL 打开函数的使用,并确保仅使用允许的协议(例如,允许 http:
和 https:
,禁止 file:
和 ftp:
)。
在 预览 中,此规则还将标记对 URL 打开函数的引用。
示例
建议改为
from urllib.request import urlopen
url = input("Enter a URL: ")
if not url.startswith(("http:", "https:")):
raise ValueError("URL must start with 'http:' or 'https:'")
with urlopen(url) as response:
...