简体   繁体   English

CSRF令牌保护的意义是什么?

[英]What is the sense of the CSRF Token protection?

I have read a lot about this and I still don't understand it. 我已经阅读了很多关于此的内容,但我仍然不理解。 Let's say I have a domain with a form available only for authenticated users to post comments on some kind of content: 假设我有一个域,该域的表单仅用于经过身份验证的用户才能对某种内容发表评论:

my_form.php my_form.php

<form action="post_comment.php" method="post">
  <textarea name="comment"></textarea>
  <input type="hidden" name="csrf_token" value="<?php print $csrf_token; ?>" />
  <input type="submit" value="Post" />
</form>

post_comment.php post_comment.php

<?php

  if(!isset($_POST['csrf_token']) || !CSRFToken::validate($_POST['csrf_token'])){
    print "Invalid CSRF-Token!";
    exit;
  }
  [...]
?>

The post_comment.php will reject any request if the "csrf_token" token value is not sent or is not valid. 如果“ csrf_token”令牌值未发送或无效,则post_comment.php将拒绝任何请求。 So we are preventing attackers to use our post_comment.php. 因此,我们防止攻击者使用我们的post_comment.php。

BUT how to prevent the attacker to GET /my_form.php, read the csrf_token value from the form and POST to post_comment.php using it? 但是如何防止攻击者获取/my_form.php,从表单读取csrf_token值并使用它发布到post_comment.php? What am I missing? 我想念什么?

The CSRF token is random and unique per session. CSRF令牌在每个会话中都是随机且唯一的。 Hence, an attacker can get the value of this token that is linked to his/her own credentials, but not to that of a potential victim. 因此,攻击者可以获得此令牌的值,该令牌链接到他/她自己的凭据,而不链接到潜在受害者的凭据。

CSRF is an attack, where the victim is logged in your site (has a session cookie), when you have no session then there is no CSRF needed. CSRF是一种攻击,受害者在您的站点中登录(具有会话cookie),当您没有会话时就不需要CSRF。 The victim visits an evil other website with the same browser. 受害者使用相同的浏览器访问其他网站。 This site can now make a post request to your site (with the cookie and therefore login of the victim), which you can prevent with CSRF Token, because while an evil site can send requests with cookies, it can not read the responses of requests (Same origin policy). 现在,此站点可以向您的站点发出请求(使用cookie并因此受害者的登录名),您可以使用CSRF令牌来阻止此请求,因为尽管恶意站点可以发送带有cookie的请求,但它无法读取请求的响应(相同的原产地政策)。 You can turn of this behavior in your (personal) Browser, but it is enabled by default, because some applications depend on it. 您可以在(个人)浏览器中关闭此行为,但是默认情况下启用了此行为,因为某些应用程序依赖此行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM