If we look at source codes of HTML forms, we typically can spot this field being rendered on the webpage
Sometimes it doesn’t have the name called CSRF Token, and it just appears as a random gibberish value being loaded.
This post breaks down the purpose of the token, and what happens behind the scenes with the token
CSRF stands for Cross-Site Request Forgery, and understanding how it works is a prerequisite to understanding CSRF tokens. Below shows a picture of what a CSRF attack looks like
- The attacker crafts a GET requests that triggers a fund transfer to his account
- The attacker embeds this request as a hyperlink
http://bank.com transfer.php?account=Attacker&amount=100"> READ MORE... </a>
- When the user clicks on the link, it triggers the
GETrequest on behalf of the victim
GETrequest is triggered by the victim, and funds are transferred to the Attacker
This attack hinges on the fact that the Victim must be logged in to the service, and is already authenticated with an open session with the service.
If the Victim is not logged in, when he clicks on the malicious link, instead of triggering the bad
GET request, it will redirect him to the login page instead, thus rendering the attack useless.
CSRF token is a simple concept where include one more argument of a token, that is sort of like a secret password.
This token value is a high-entropy value which is hard to guess by the attacker. If on the server side, it receives a wrong or missing CSRF token value, the
GET request is rejected and does not execute
The CSRF token works this way:
- Client requests for a HTML page that contains a form
- Server generates two distinct tokens, and sends one as a cookie to the client, and embeds the other as a hidden field in the form
- When the client submits the form, both CSRF tokens must be sent back to the server. The one embedded in the form, and the one in the cookie.
- If the request does not contain both tokens, it’s rejected
The CSRF token value should be regularly invalidated at a time interval, per request, or when the user logs out.
CSRF Token Vulnerabilities
If traffic carrying the token is not encrypted over HTTPS, the Attacker can sniff the traffic and obtain the CSRF token value and the Cookie, and perform a CSRF token replay attack.
The solution to this is obvious: Always use encryption for communication. Aside from that, per-request-tokens can also be implemented.