Rails Ruby on Rails 教程 第 8 章

bmiwdmb · 2015年02月13日 · 最后由 andor_chen 回复于 2016年11月28日 · 2225 次阅读

http://railstutorial-china.org/book/chapter8.html#listing-failed-login-attempt

Ruby on Rails 教程 第 8 章中實現一個 cookie 記住密碼。其中有一段提到

其中,cookies.signed[:user_id] 会自动解密 cookie 中的用户 ID。然后,再使用 bcrypt 确认 cookies[:remember_token] 和 代码清单 8.32 生成的 remember_digest 是否匹配。(你可能想知道为什么不能只使用签名的用户 ID。如果没有记忆令牌,攻击者一旦知道加密的 ID,就能以这个用户的身份登录。但是按照我们目前的设计方式,就算攻击者同时获得了用户 ID 和记忆令牌,也要等到用户退出后才能登录。)

不太理解

但是按照我们目前的设计方式,就算攻击者同时获得了用户 ID 和记忆令牌,也要等到用户退出后才能登录

這句話的意思

可以請前輩們解惑嘛 感謝!(如果可以的話希望可以解釋一下來龍去脈,感謝!)

匿名 #1 2015年02月13日

看书,最好是看原版:https://www.railstutorial.org/book/log_in_log_out, 大概的给你解释下吧: 正常流程是: 1.Create a random string of digits for use as a remember token. 2.Place the token in the browser cookies with an expiration date far in the future. 3.Save the hash digest of the token to the database. 4.Place an encrypted version of the user’s id in the browser cookies. 5.When presented with a cookie containing a persistent user id, find the user in the database using the given id, and verify that the remember token cookie matches the associated hash digest from the database.

关键是第 5 条,每次登陆都会随机生产 remember token。

至于你不理解的 内容 (In case you’re wondering why we don’t just use the signed user id, without the remember token, this would allow an attacker with possession of the encrypted id to log in as the user in perpetuity. In the present design, an attacker with both cookies can log in as the user only until the user logs out.) 我这样给你讲,看你能不能理解:

如果只校对 user_id,那么 attacker 拥有 user_id 的话,attacker 就可以随时非法登陆。 现在的情况是,同时校对 user_id 和 remember token(user_id 的校对是通过查找 remember_digest 体现的),那么现在 attacker 非法登陆的话,就会产生一个新的 remember_token,这样真正的用户就再也无法登陆(此处特指无法用 cookie 登陆,提交表单还是可以登陆的),注意注意,现在关键的东西来了:你反过来想,你交换上一句话中的 attacker 和真正用户的位置,你就可以得出结论:attacker 想要利用 cookie 登陆,只能趁 remember_token 没改变的时候登陆,什么时候 remember_token 不会变——那就是真正用户 log out 之后,下一次 log in 之前。

😄

以后还是多看原版书,可能会吃力,但是绝对不会吃亏。

@fuan 感謝前輩解惑<(_ _)> 英文苦手阿...,第九章之後就剩下英文版可以看了... 自己也在努力訓練英文閱讀...

匿名 #3 2015年02月13日

#2 楼 @bmiwdmb 快速提高英文能力可以考虑报个培训班,有人带,有人陪,学的更快,更开心;花了钱也会学的更上心。google 下“快速提高英文阅读 培训班”,选个离你上班近点的,就好。

@fuan 哈哈 高三生還有沒有可塑性阿 (其實我知道要幹這行英文無比重要)

匿名 #5 2015年02月13日

#4 楼 @bmiwdmb 可塑性超强。😄 学生好多了,记忆力好,身体壮,单纯(父母也是壮年,配偶也够挑,谈不上下一代什么的,自己的话经济没什么开销,也不用赚钱。一句话,可以全身心的投入到任何事情上,并且能够全身而退。)。。。。有时候我会觉得,中学时代是寄生时代(no offense)。。。 具体说到英语上的话,挺简单的,你只需要全身心投入就行。

#1 楼 @fuan 你这个解释实际上误导楼主 @bmiwdmb

如果攻击者有这 2 个 cookie,他当然是直接劫持了,直接使用窃取的 user_id 和 remember_token 访问网站,无需经过任何表单就能达到认证的效果。所以根本不会调用 SessionHelper#remember,所以也不会调用 User#remember,所以并不会"产生一个新的 remember_token"

问题的关键其实在于中文翻译(译者和你同样都理解反了)

an attacker with both cookies can log in as the user only until the user logs out

英文肯定句中的 until 跟 till 是一个意思,最后一句的翻译是"但是按照我们目前的设计方式,就算攻击者同时获得了用户 ID 和记忆令牌,至多只能维持登录状态到真正的用户登出"。因为真正的用户登出后,SessionsHelper#forget 会重置数据库中的 remember_digest,因而攻击者的 cookies 也失效了。而原先的翻译是没有办法解释通的。

#6 楼 @nostophilia 谢谢指出这个问题,我会再次确认。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号