Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to does the token prevent csrf attack?

I have read about CSRF and how the Unpredictable Synchronizer Token Pattern is used to prevent it. I didn't quite understand how it works.

Let's take this scenario :

A user is logged into a site with this form:

<form action="changePassword" method="POST">    <input type="text" name="password"><br>    <input type="hidden" name="token" value='asdjkldssdk22332nkadjf' > </form> 

The server also stores the token in the session. When the request is sent it compares the token in the form data to the token in the session.

How does that prevent CSRF when the hacker can write JavaScript code that will:

  1. Send a GET request to the site
  2. Receive html text containing the request form.
  3. Search the html text for the CSRF token.
  4. Make the malicious request using that token.

Am missing something?

like image 276
david Avatar asked Jul 09 '15 16:07

david


People also ask

How does CSRF token prevent CSRF?

CSRF tokens can prevent CSRF attacks by making it impossible for an attacker to construct a fully valid HTTP request suitable for feeding to a victim user.

How can CSRF attacks be prevented?

What Are CSRF Tokens. The most popular method to prevent Cross-site Request Forgery is to use a challenge token that is associated with a particular user and that is sent as a hidden value in every state-changing form in the web app.

How does CSRF token work?

A CSRF token is a secure random token (e.g., synchronizer token or challenge token) that is used to prevent CSRF attacks. The token needs to be unique per user session and should be of large random value to make it difficult to guess. A CSRF secure application assigns a unique CSRF token for every user session.

How do I know if my CSRF token is working?

A couple of ways you can test it: Open the developer tools in your browser find the input element for the CSRF token and edit the token value. Trigger a POST submission. This should cause an error, HTTP status 403 typically.


1 Answers

The attacker can't use JavaScript to read the token from the site, because it would be a cross-origin request and access to the data from it is blocked (by default) by the Same Origin Policy (MDN, W3C).

Take this for example:

var xhr = new XMLHttpRequest();  xhr.open("GET", "http://google.com");  xhr.addEventListener('load', function (ev) {      console.log(this.responseText);    });  xhr.send();

The JS console reports:

XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource.

like image 134
Quentin Avatar answered Oct 04 '22 04:10

Quentin