API Security: Learn about CSRF
Oct 24, 2022
By
Puneet verma
Cross-site request forgery (CSRF) is a web security vulnerability that allows attackers to induce users to perform actions they do not intend to perform.
It's worth noting malicious site didn't get the cookies(Browser restricts that). Scripts from site A can't access the cookies of site B. But. as the request goes to bank.com, the browser allows cookies of bank.com.
How to overcome?
The attack is possible only if mybank.com uses cookies to identify the legitimate user.
- We can avoid these attacks by adding some random variables in the form. These variables are called CSRF token
- Every time bank.com will bind the request form with a secret random code
- The attacker has the information of static form but doesn't have information about dynamic token
- Every request server will match cookies (having a user session) with the CSRF token. The request will be executed only if the pair is matched
In this case, the origin of the request will be the malicious website only, so if the server checks the request origin, then their no need for any other token itself.
Why can't we use curl or any other software to send the request?
You can send the request, but the user cookies will not be available to you.
Why would the server send the request when it knows that the origins don’t match?
It does this because cross-site requests are quite common and make the web usable, efficient, and fast for us. In fact, for certain types of requests and when REST semantics are implemented correctly, there is no security concern (well, specifically related to cross-origin security - there is never a situation where there is NO security concern).
Does a proper CORS setup prevent CSRF attack?
To be more specific, it is easy to make the mistake of thinking that if evil.example
cannot make a request to good.example
due to CORS then CSRF is prevented. There are two problems being overlooked, however:
-
CORS is respected by the browsers only. That means Google Chrome will obey CORS and not let evil.example
make a request to good.example
. However, imagine someone builds a native app or whatever which has a form that POSTs things to your site. XSRF tokens are the only way to prevent that.
-
Is it easy to overlook the fact that CORS is only for JS request. A regular form on evil.example
that POSTs back to good.example
will still work despite CORS.
For these reasons, CORS is not a good replacement for XSRF tokens. It is best to use both.