33
votes

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?

2

2 Answers

20
votes

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.

-2
votes

It's important to realize that CSRF attacks only happen in the browser. The user's session with the target server is used by the malicious server to forge requests. So how does #1 happen? Two options: you could make the #1 request from the malicious server, but that would simply return a CSRF token for the server's session, or you could make the #1 request using AJAX which, as you correctly identified, would return the CSRF token of the victim user.

Browsers have implemented HTTP access control for this very reason. You must use the Access-Control-Allow-Origin header to restrict which domains may make AJAX requests to your server. In other words your server will ensure the browser doesn't let the malicious site do #1. Unfortunately the documents I've read on the matter aren't very clear about it, but I think that's because servers by default do not send an Access-Control-Allow-Origin header unless configured to do so. If you do need to allow AJAX requests, you must either trust any origins in the header not to perform a CSRF attack, you can selectively lock down sensitive portions of your application to not allow AJAX requests, or use the other Access-Control-* headers to protect yourself.

Using a Synchronizer Token is one way that an application can rely upon the Same-Origin Policy to prevent CSRF by maintaining a secret token to authenticate requests

https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet

You should read up on Cross-Origin Resource Sharing (CORS).