Web Application Security Guide/Cross-site request forgery (CSRF)

Cross-site request forgery (CSRF)

Cross-site request forgery occurs if a third-party web site causes the browser of the logged-in user to make a request to your service. With GET forms, this can be done using IFRAMEs or IMG tags. With POST forms, this is possible using a FORM element with the action attribute pointed to your site, possibly submitted using JavaScript. Both methods require no user interaction. The browser automatically submits the session cookie of the user. This can allow an attacker to trigger unwanted action with the permissions of the logged-in user.

To prevent this type of attack

  • Include a hidden form field with a random token bound to the user’s session (and preferably the action to be performed), and check this token in the response
  • Make sure the token is non-predictable and cannot be obtained by the attacker
    • do not include it in files the attacker could load into his site using <script> tags
  • Referer checks are not secure, but can be used as an additional measure

Rationale

CSRF attacks allow attackers to abuse existing user sessions. The same-origin-policy of web browsers prevents the attacking web site to read the content (and thus the token) of the targeted site. As the token is bound to the session, the attacker cannot gain the token by simply visiting the web site himself. The token needs to be non-predictable (secure randomness), as otherwise the attacker could simply guess it.

Referer checks are unreliable, as some user agents do not send the header and some personal firewalls filter or falsify it for privacy reasons. Additionally the attacker can avoid sending a Referer, for example (tested with IE8 and Firefox 6) simply by setting window.location using JavaScript.