What is CSRF Synchronizer Token Pattern?

CSRF or Cross-Site Request Forgery is a well known security attack that is listed in OWASP security risks. CSRF is basically running malicious JavaScript code pieces to a targeted website without the knowledge of the browser user. It is more target centric attack where intruder has to know what s/he wants to perform.

Synchronizer Token Pattern is a very simple concept to mitigate the risk of being attacked through CSRF. In most web applications, servers are using HTTP session objects to identify the logged in users. In this case, session is generated in the server side and pass the session ID to the client. This session ID is most of the time is saved in a client side cookie file.

Because of this session ID is being saved in client side cookie file, if the cookie is not protect with advanced configurations(httponly, samesite, secure, etc), it is possible to access this cookie from another page that has open in the client browser. That is probably in a different browser tab.

It is possible that in JavaScript we can access dynamically create an html form without a UI and submit it to a given endpoint. This way, intruder can even withdraw money from your account without your awareness. You can be happy visiting an intruder web page, but it will internally withdraw money from your fakebank account.

There is a nice StackOverflow question and an answer on Synchronizer Token Pattern.

I have implement how this pattern can avoid CSRF in the below github repository. It analogues with the StackOverflow question.

The tricky part is on 6. point. Legit user has a hidden token which was generated in the server side. There is a mapping between the session ID and this generated CSRF token. Therefore, when we make the 6. withdraw call, server will check whether client has provided that particular CSRF token embedded in the HTML form. End user has no clue that there was a hidden form field in that HTML form.

On the other hand, intruder doesn’t know that there is a CSRF token associated with the session ID. So, when s/he tries to withdraw the money, server will compromise that it is a malicious request.

Note: It is possible to think why in the world that intruder just obtain that particular CSRF token and make the request? Simple answer is, it is because this whole thing happens in someone’s browser. It is not happened in intruder’s premises. Refer to the above Stack Overflow question for more details.