CORS 配置错误检测 —— 原理、示例与自动化检测
为了让前端能跨域调接口,服务端要回 Access-Control-Allow-Origin。一旦这个值直接回显请求的 Origin,再配上 Allow-Credentials: true,任何网站都能带着用户的 Cookie 读我们的接口,跨域隔离就失效了。
漏洞危害
- 任意站点读取登录用户的私有数据
- 配合 CSRF 形成完整攻击链:读 + 写
- 把内网管理接口暴露给外部页面调用
代码示例(Python)
❌ 危险写法
# 危险写法:Origin 原样回显 + 允许携带凭据
@app.after_request
def add_cors(resp):
resp.headers["Access-Control-Allow-Origin"] = request.headers.get("Origin")
resp.headers["Access-Control-Allow-Credentials"] = "true"
return resp
✅ 安全写法
# 安全写法:白名单比对,不命中就不回 CORS 头
ALLOWED = {"https://xinpect.xingwangzhineng.com"}
@app.after_request
def add_cors(resp):
origin = request.headers.get("Origin")
if origin in ALLOWED:
resp.headers["Access-Control-Allow-Origin"] = origin
resp.headers["Access-Control-Allow-Credentials"] = "true"
resp.headers["Vary"] = "Origin"
return resp
煋鉴如何检测
- Allow-Origin 取值来自请求头,或写死为 * 且同时允许凭据
- 用 startswith / endswith 匹配域名(evil-xinpect.com 也能过)
- 预检响应里放开了 Allow-Headers 与 Allow-Methods 但没做来源校验