CSRF attack and solution
Background
csrf, which is Cross-site request forgery, is a kind web attack base on the fact that cookies is attached in every request, no matter who is the initiator. The initiator can be the true user which get the credential token for logging in, or the evil who secretly ask you to trigger the request and attached your token.
In a simple view, the evil.sample
can you a hidden link that trigger the request to your.bank
. But you wont notice it was a link to your bank, that may transfer money out. Once you click the link, the request will fire and the associated token which you got from the bank a few minute ago will attached with the request. Hence the evil.sample
can get your money from your.bank
.
Solution
There is two main stream solutions to tackle this problem:
-
CSRF token
the main concept of CSRF token is to issue a object that only the real user know and the
evil.sample
cannot not get it from any way. To achieve this, server will issue a random token to user in every session. User need to attach that random token to the sever and the server will check if it exists in their session. As theevil.sample
can never wild guess the token, user can prevent pro csrf attack. -
SameSite cookies attribute
the main concept of SamSite cookies attribute is to set that particular cookie to be restricted to same-site context. In normal practice, when the genuine user is visiting your site and get the token from server, and request data with the given token, the cookie will be attached as usual. But if the user click on a link from friend via email link or website, like
evil.example
. the cookie will not be attached to the request and the request will broke. We can achieve this bySet-Cookie: flavor=mintChoco; SameSite=Lax
to enable SameSite cookies.
Fun Fact
SameSite attribute is default to all cookie starting from Chrome 80. SameSite attribute will be set to Lax
by default if not specify.