### 漏洞概述 该漏洞涉及一个不安全的CORS(跨源资源共享)策略,允许跨源攻击。在`on_prepare`处理程序中,无条件地将Origin请求头反射到`Access-Control-Allow-Origin`响应头中,并且当`cors_allowed_origins`配置为空时,允许所有API端点的跨源请求。这导致任何网站都可以进行跨源下载、Cookie覆盖和数据删除。 ### 影响范围 - **跨源下载**:任何网站都可以发起跨源下载请求。 - **Cookie覆盖**:攻击者可以通过跨源请求覆盖用户的Cookie。 - **数据删除**:攻击者可以执行跨源数据删除操作。 ### 修复方案 通过引入一个显式的白名单机制来替换原来的空白Origin反射。使用`CORS_ALLOWED_ORIGINS`环境变量变量,默认情况下拒绝所有跨源请求。用户可以通过逗号分隔的受信任来源列表来配置`CORS_ALLOWED_ORIGINS`。 ### POC代码 ```python # 修复前的代码片段 @app.on_prepare def on_prepare(request, response): if 'Origin' in request.headers: response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] origin = request.headers.get('Origin') if origin and _cors_origins and origin in _cors_origins: response.headers['Access-Control-Allow-Origin'] = origin response.headers['Access-Control-Allow-Headers'] = 'Content-Type' # 修复后的代码片段 # 在配置文件中添加 'CORS_ALLOWED_ORIGINS': '', # 在代码中处理 _cors_origins = [o.strip() for o in config.CORS_ALLOWED_ORIGINS.split(',') if o.strip()] if config.CORS_ALLOWED_ORIGINS else [] @app.on_prepare def on_prepare(request, response): if 'Origin' in request.headers: origin = request.headers.get('Origin') if origin and _cors_origins and origin in _cors_origins: response.headers['Access-Control-Allow-Origin'] = origin response.headers['Access-Control-Allow-Headers'] = 'Content-Type' ```