Reputation: 396
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
<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
<?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. So we are preventing attackers to use our 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? What am I missing?
Upvotes: 2
Views: 477
Reputation: 1858
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. 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). You can turn of this behavior in your (personal) Browser, but it is enabled by default, because some applications depend on it.
Upvotes: 0
Reputation: 6650
The CSRF token is random and unique per session. 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.
Upvotes: 3