tags : Security, Cookies, CORS, Web Security, Web Authentication

Cross Site Request Forgery

It an attack

Nature of the attack

  • It’s a server side concern. Any API request that the server gets that alters server state should make sure it’s a legit request. This is usually done via a “CSRF check”.
  • It does not attempt direct theft of data because the attacker does not see the response of the forged request because of Same Origin Policy (SOP) and appropriate CORS configuration.

Some ways CSRF attack can happen

  • You’re logged in bank.com, Cookies are there
  • evil.com has a link bank.com?tranfer=1000, by clicking on that link you’ll execute the thing because you’re logged in
  • Solution: Use samesite attribute for the cookie w appropriate value

Form submit on page load

  • evil.com can contain a hidden form that submits POST on page load to bank.com. Your cookies used indirectly by attacker.
  • The response from bank.com to evil.com will be a cross-origin response and Same Origin Policy (SOP) will drop that response but since the POST request already happened(Because SOP allows cross-origin writes!) and the server processed it does not care about that response getting dropped cuz Same Origin Policy (SOP)
  • Prevention
    • This can be prevented if bank.com took a CSRF token(session based) along with the POST request. evil.com would not have access to CSRF token.
    • This CSRF Token should be stateless, should be part of the POST request and not be stored anywhere(cookie, localstoage etc)
    • This has to be done at application code level, can’t be done at proxy level.

Prevention mechanisms

  • See Cookies
  • This is a client side
  • SameSite will help mitigate certain class of CSRF attacks.
  • SameSite=Lax still allows form submissions from subdomains of your primary domain to carry their cookies. So we still need csrf token.

Using the CSRF token in DOM

  • Anti-CSRF tokens generally should not be stored in cookies but can be stored anywhere in the DOM and can be extracted via javascript and set back to the server via X-CSRF-Token header.
  • The auth details remain in cookie, a custom session only csrf token is baked into the DOM.
  • This way evil.com even if it does CSRF using hidden form etc, because of lack of csrf token they’ll fail.