Does ASP.NET Viewstate implicitly prevent CSRF attacks? What does this mean for MVC?

The purpose of ASP.NET ViewState is to persist control state between post-backs (see MDSN explanation), it does not implicitly enable security that would prevent CSRF.

Also note that encrypted ViewState in unpatched older versions of ASP.NET are susceptible to an encryption vulnerability.

To enable this type of protection you could:

  • Use ViewStateUserKey (See a high level description of the feature, the MSDN docs for ViewStateUserKey and the OWASP CSRF prevention cheat sheet.

  • Use a custom method to render a custom managed hidden field (per transaction) in the form and check for it with each client request.

  • Use a third party library dedicated to CSRF such as AntiCSRF.

ASP.NET MVC3 does have an anti-forgery token that is used with the [ValidateAntiForgeryToken] attribute on the controller action (See http://msdn.microsoft.com/en-us/library/system.web.mvc.validateantiforgerytokenattribute.aspx). In the view’s form tag call the Html.AntiForgeryToken helper (See http://msdn.microsoft.com/en-us/library/dd470175.aspx) with following syntax:

Web Forms:

<%= Html.AntiForgeryToken() %>

Razor:

@Html.AntiForgeryToken()

It is difficult to execute a successfull CSRF attack on an application using viewstate but not impossible. One way to do a succcessful CSRF attack on an application with _viewstate is

  1. Attacker is able to login to the application ( using own or aquired credentials)
  2. Visit the page (with most common or most useful variable states) against which she wants to create a CSRF attack for
  3. Copy the _Viewstate
  4. Insert this _viewstate in her attack page
  5. Send the attack page to the victim
  6. With some luck and good guessing the attack might just work

A solution to this has been introduced in 1.1. Instead of using just _viewstate you can use ViewStateUser-Key . This uses the use session key to create the state token which will be really difficult to guess or copy by the attacker.

I would still suggest implementing an indenpendent CSRF token mechanism for protection against CSRF in your application ( I know many will differ on this)