flask CSP ( Content-Security-Policy ) 对抗跨站脚本等攻击的最佳实践

flask CSP ( Content-Security-Policy ) best practice against attack such as cross site scripting

我是 CSP 新手。我试图通过设置 resp_header 来保护我的网站免受 Cross-Site 脚本攻击,从而在我的 Flask 应用程序的所有模板中实施 CSP。我修改了我的渲染模板:

return render_template('addvideos.html'  form=form, legend = 'Update video : '+ videos.video_name)

    resp = make_response(render_template('addvideos.html', legend = 'Update video : '+ videos.video_name)
)
    resp.headers['Content-Security-Policy'] = "default-src 'self';"
    return resp

我在应用程序中有超过 50 个“render_template”,我必须为每个添加一个响应 header。经过研究,我发现 after_request 会起到如下所示的作用:

@app.after_request
def add_security_headers(resp):
    resp.headers['Content-Security-Policy']='default-src \'self\''
    return resp

这个靠谱吗?如果我直接在 HTML 模板 ( jinja2 ) 中应用 CSP,这可能吗?哪个更靠谱?

is this very reliable ?

是的。在 app.after_request 装饰器中设置 header 将 header 应用到该 app.

服务的所有路由

What if I apply the CSP directly in the HTML template ( jinja2 ), is that possible?

这不是模板本身可以完成的事情,您可以像上面那样在 Python 中设置 header。

Which is more reliable ?

虽然前一种方法(通过 app.after_request 装饰器)有效,但它通常可以由 Python 应用服务器位于其后的反向代理来处理。如果不熟悉,请查看 the deployment docs.

例如,使用 nginx 作为反向代理,您可以将其放在 server 块中:

add_header Content-Security-Policy "default-src 'self';";

或者,发送 header 而不管响应代码:

add_header Content-Security-Policy "default-src 'self';" always;

This blog 有一些关于是让反向代理处理发送这个 header 还是在你的 Flask 应用程序中定义它的好建议:

Should I add a CSP header with nginx or my in application? While it is certainly easy to add a CSP header with nginx, it also possible to add a Content-Security-Policy header with your server side programming language ([Flask]). There are tradeoffs to doing it either way. If you have sections of your application that may require a different CSP policy then it might be easier to use your application programming language instead. Or if you plan to use features such as a CSP nonce, then it is much easier to set the Content-Security-Policy from your application code instead of from nginx.

此外,如果您要部署到像 Heroku 这样的平台,该平台在基本配置中会直接公开 gunicorn 应用服务器,那么在您的应用中设置此 header 可能会更容易,除非您打算去进一步部署一个 nginx 构建包。

其他基于云的负载均衡器可能会提供自己的方式来设置这些 header,与您的应用无关。

配置反向代理或负载平衡器时,值得一看 Mozilla's SSL Configuration Generator which supports nginx, AWS ALB/ELB and others. The server can then be tested with Qualys SSL test