gpt4 book ai didi

node.js - 如果 session cookie 是安全的,则 CSURF 不工作

转载 作者:可可西里 更新时间:2023-11-01 10:25:36 28 4
gpt4 key购买 nike

我很困惑,当我将 cookie 设置为安全时, Node 的 csrf 不工作。

//Load Cooike Parser
app.use(cookieParser(secret));
//Load Session Store
app.use(require('express-session')({
secret:secret,
cookie:{
maxAge: 1000 * 60 * 60 * 24, // 1 day,
secure: true,
httpOnly: true
},
store: sessionStore
}));
//Load POST data parser
//Form sent should be in JSON format
app.use(bodyParser.json());

//Initiate CSRF on middleware
//set the CSRF cookie Header
app.use(csrf());
app.use(function(req,res,next){
res.cookie('XSRF-TOKEN',req.csrfToken());
next();
});

此设置使用 MongoDB 存储 session 数据。阅读 express-session 文档,我发现了这个......

Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set. If you have your node.js behind a proxy and are using secure: true, you need to set "trust proxy" in express:

来源: npm express-session

我目前在本地运行网站,因此它不是 HTTPS。我想知道 secure:true 与未通过 csrf 测试有什么关系?

最佳答案

由于所提供的代码示例未涵盖表单的创建,因此我假设您正确地包含了 _csrf 值。或者您使用 JavaScript 设置相应的 header 。

让我们首先解释为什么您不应该执行 res.cookie('XSRF-TOKEN',req.csrfToken());

csurf 模块的默认工作方式是在您运行 req.csrfToken() 时生成或返回 _csrf token ,但它还将此 token 保存在 session 中。

如果您想使用 cookie 而不是 session 作为存储方法,您应该将 cookie: truecookie: cookieOptions 作为初始化值传递给 csurf 而不是手动设置 cookie。

这是相关的,因为如果您不使用预期的选项参数,csurf 将尝试从 session 对象中查找 token 值以进行验证,这意味着您的 cookie 设置是无用的。

现在关于它在 HTTPS 上失败的部分。

当您设置 secure: true 时,它所做的是使用 secure 标志从服务器向浏览器发送 cookie。

根据 OWASP page :

The secure flag is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure flag is to prevent cookies from being observed by unauthorized parties due to the transmission of a the cookie in clear text.

To accomplish this goal, browsers which support the secure flag will only send cookies with the secure flag when the request is going to a HTTPS page. Said in another way, the browser will not send a cookie with the secure flag set over an unencrypted HTTP request.

这包括 session token cookie,用于在 sessionStore 中查找信息。

因此浏览器不会向服务器发送 session cookie。服务器创建一个新的空 session ,因为我们返回到默认的 csurf 操作方法,它将尝试从空 session 中查找 token 。不会有 token ,因此比较会失败。

作为旁注,这也意味着您的 session 通常会失败。

注意!作为旁注,如果您更感兴趣,我建议您阅读 OWASP CSRF mitigation cheatsheet .或者我关于 Node.js Web Application Security 的书,其中包括 CSRF 和使用 Node.js 实现的各种缓解方法。

关于node.js - 如果 session cookie 是安全的,则 CSURF 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34414106/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com