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:
Am missing something?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With