CSRF代币生成 [英] CSRF token generation

查看:71
本文介绍了CSRF代币生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有关生成CSRF令牌的问题。

This is a question about generating CSRF tokens.

通常,我想根据与用户会话相关的唯一数据生成令牌,

Usually I'd like to generate a token based off of a unique piece of data associated with the user's session, and hashed and salted with a secret key.

我的问题是关于在没有唯一的用户数据要使用时生成令牌的问题。没有可用的会话,不是cookie的选择,IP地址以及类似性质的东西都不可靠。

My question is in regards to generating tokens when there is NO unique user data to use. No sessions are available, cookies are not an option, IP address and things of that nature are not reliable.

我是否有任何理由无法将要哈希的字符串包括为要求的一部分呢?
生成令牌并将其嵌入的示例伪代码:

Is there any reason why I cannot include the string to hash as part of the request as well? Example pseudocode to generate the token and embed it:

var $stringToHash = random()
var $csrfToken = hash($stringToHash + $mySecretKey)
<a href="http://foo.com?csrfToken={$csrfToken}&key={$stringToHash}">click me</a>

CSRF令牌的服务器端验证示例

Example server-side validation of the CSRF token

var $stringToHash = request.get('key')
var $isValidToken = hash($stringToHash + $mySecrtKey) == request.get('csrfToken')

散列中使用的字符串在每个请求上都不同。只要它包含在每个请求中,CSRF令牌验证就可以继续。由于它在每个请求中都是新的,并且仅嵌入在页面中,因此无法使用外部访问令牌。令牌的安全性将落入$ mySecretKey,只有我自己知道。

The string being used in the hash would be different on each request. As long as it was included in each request, the CSRF token validation could proceed. Since it is new on each request and only embedded in the page, outside access to the token would not be available. Security of the token then falls to the $mySecretKey being known only to me.

这是一种幼稚的方法吗?我是否因为某些原因而无法正常工作?

Is this a naive approach? Am I missing some reason why this cannot work?

谢谢

推荐答案

我是否有任何原因不能将要哈希的字符串也包含在请求中?

CSRF令牌有两个部分。嵌入在表单中的令牌以及其他位置的相应令牌(在cookie中,存储在会话中或其他位置)。

CSRF tokens have two parts. The token embedded in the form, and a corresponding token somewhere else, be it in a cookie, stored in a session or elsewhere. This use of elsewhere stops a page being self contained.

如果在请求中包含要哈希的字符串,则请求是自包含的,因此复制表单是全部攻击者需要这样做,因为它们都有令牌的两个部分,因此没有保护。

If you include the string to hash in the request, then the request is self contained, so copying the form is all an attacker needs to do, as they have both parts of the token, and thus there is no protection.

即使将其放在URL形式中,也意味着它是自包含的,攻击者只需复制表单和提交URL。

Even putting it in the form URL means that it's self contained, the attacker simply copies the form and the submission URL.

这篇关于CSRF代币生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆