Fight Off Forgery Attacks

Use ASP.NET MVC to fend off intruders.

Dark Reading Staff, Dark Reading

August 4, 2010

2 Min Read
Dark Reading logo in a gray background | Dark Reading

Modern browsers fend off cross-site scripting attacks. But there's another type of attack that is even easier to launch: cross-site request forgery.

CSRF attackers set up a Web page with clickable elements that trigger malicious operations. The fake page typically contains hidden script code that collects data from a local computer and posts it to the attacker's server.

How can you protect yourself? ASP.NET MVC offers a solution. It lets you publish server functionalities through a public method of a controller class. If the method is critical, you can add attributes to prevent CSRF attacks. ASP.NET MVC provides a helper method to generate ad hoc HTML markup and a ValidateAntiForgeryToken attribute:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Update
 (Customer customer)
{
 :
}

The HttpPost attribute requires a POST request to execute the method. This alone cuts off any requests made through a plain GET. ValidateAntiForgeryToken also instructs the invoker of the ASP.NET MVC method to look for some special content in the request body before executing the code.

ValidateAntiForgeryToken contains code activated during an action method request, ensuring the posted request contains a cookie and a form field with a common fixed name. If any of these items are missing, an exception is thrown.

This ASP.NET MVC HTML helper lets you insert this content into a Web page:

<%= Html.AntiForgeryToken() %>

The Html.AntiForgeryToken method creates a cookie on your machine and adds a hidden field like this to the form:

<input name="__RequestVerificationToken" type="hidden"
value="j3Cj++/JUcS+kUMy/9Obj/oM6ZW7vZozNo7+S" />

If the target of the form includes the ValidateAntiForgeryToken attribute, the content of the cookie and input field are matched before the action method is authorized. Thus, intruders can't create valid cookies because they don't know what content to put in them. And even if the victim's machine already contains an anti-forgery cookie, the content of the cookie can't be read via script to arrange a form input field on-the-fly. An anti-forgery cookie, in fact, is HttpOnly and can't be accessed via script.

Dino Esposito is a Microsoft MVP and independent software consultant.

Read more about:

2010

About the Author

Dark Reading Staff

Dark Reading

Dark Reading is a leading cybersecurity media site.

Keep up with the latest cybersecurity threats, newly discovered vulnerabilities, data breach information, and emerging trends. Delivered daily or weekly right to your email inbox.

You May Also Like


More Insights