ASP .NET MVC CSRF Breakdown

Cross-Site Request Forgery(CSRF) is in the Open Web Application Security Project(OWASP) top 10 2013 edition. OWASP is a non profit organization that produces a list of the top security vulnerabilities in order to help improve web software security. In the top 10 edition for 2013 the CSRF security vulnerability is #8, slipping all the way from #5 in the 2010 OWASP list. This is likely due to frameworks that provide anti-forgery tokens to reduce the CSRF vulnerability.

How does Cross-Site Request Forgery Work?

It is very common to store the websites authentication info in a Cookie. Cookies are automatically passed back and forth on every request to the web application, so it's a convenient method of passing security info to your web application.

The simplest way to demo this in the most basic sense is login to your website. Open a new tab and go to your website. Notice you are still logged into the website.

ASP .NET MVC Anti Forgery Token

In ASP .NET MVC there is a built in HTML helper called that you use inside a <form> tag like so @Html.AntiForgeryToken(). This little helper does quite a few things on your behalf

  • sets a cookie called __RequestVerificationToken
  • creates a hidden input tag like <input name="__RequestVerificationToken" type="hidden" value="Wq2QX6P4GuYQ3ByivO2-zmZ4AfFak3TEjlj4mTGVbxH3s1WkIC-dZoF0HqBML-DHkpIQfjepoeOdQdV8OEh_kwnixd41" />
  • adds the Response header X-Frame-Options: SAMEORIGIN

To validate a form POST you would then add the ValidateAntiForgeryToken attribute to your receiving controller's action method. For example,

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateSomething(AccountModel model)  
{
    // etc...
}

The ValidateAntiForgeryToken is a filter that checks three things on the incoming post request.

  1. There is a cookie called __RequestVerificationToken
  2. There is a form field called __RequestVerificationToken
  3. The cookie token and form token cryptographically match

References