Wednesday, April 14, 2010 10:50 AM srkirkland

Guarding against CSRF Attacks in ASP.NET MVC2

Alongside XSS (Cross Site Scripting) and SQL Injection, Cross-site Request Forgery (CSRF) attacks represent the three most common and dangerous vulnerabilities to common web applications today. CSRF attacks are probably the least well known but they are relatively easy to exploit and extremely and increasingly dangerous. For more information on CSRF attacks, see these posts by external link: Phil Haack and external link: Steve Sanderson.

The recognized solution for preventing CSRF attacks is to put a user-specific token as a hidden field inside your forms, then check that the right value was submitted. It's best to use a random value which you’ve stored in the visitor’s Session collection or into a Cookie (so an attacker can't guess the value).

ASP.NET MVC to the rescue

ASP.NET MVC provides an HTMLHelper called AntiForgeryToken(). When you call <%= Html.AntiForgeryToken() %> in a form on your page you will get a hidden input and a Cookie with a random string assigned.

Next, on your target Action you need to include [ValidateAntiForgeryToken], which handles the verification that the correct token was supplied.

Good, but we can do better

Using the AntiForgeryToken is actually quite an elegant solution, but adding [ValidateAntiForgeryToken] on all of your POST methods is not very DRY, and worse can be easily forgotten.

Let's see if we can make this easier on the program but moving from an "Opt-In" model of protection to an "Opt-Out" model.

Using AntiForgeryToken by default

In order to mandate the use of the AntiForgeryToken, we're going to create an ActionFilterAttribute which will do the anti-forgery validation on every POST request.

First, we need to create a way to Opt-Out of this behavior, so let's create a quick action filter called BypassAntiForgeryToken:

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
public class BypassAntiForgeryTokenAttribute : ActionFilterAttribute { }

Now we are ready to implement the main action filter which will force anti forgery validation on all post actions within any class it is defined on:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class UseAntiForgeryTokenOnPostByDefault : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (ShouldValidateAntiForgeryTokenManually(filterContext))
        {
            var authorizationContext = new AuthorizationContext(filterContext.Controller.ControllerContext);
 
            //Use the authorization of the anti forgery token, 
            //which can't be inhereted from because it is sealed
            new ValidateAntiForgeryTokenAttribute().OnAuthorization(authorizationContext);
        }
 
        base.OnActionExecuting(filterContext);
    }
 
    /// <summary>
    /// We should validate the anti forgery token manually if the following criteria are met:
    /// 1. The http method must be POST
    /// 2. There is not an existing [ValidateAntiForgeryToken] attribute on the action
    /// 3. There is no [BypassAntiForgeryToken] attribute on the action
    /// </summary>
    private static bool ShouldValidateAntiForgeryTokenManually(ActionExecutingContext filterContext)
    {
        var httpMethod = filterContext.HttpContext.Request.HttpMethod;
 
        //1. The http method must be POST
        if (httpMethod != "POST") return false;
 
        // 2. There is not an existing anti forgery token attribute on the action
        var antiForgeryAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), false);
 
        if (antiForgeryAttributes.Length > 0) return false;
 
        // 3. There is no [BypassAntiForgeryToken] attribute on the action
        var ignoreAntiForgeryAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(BypassAntiForgeryTokenAttribute), false);
 
        if (ignoreAntiForgeryAttributes.Length > 0) return false;
 
        return true;
    }
}

The code above is pretty straight forward -- first we check to make sure this is a POST request, then we make sure there aren't any overriding *AntiForgeryTokenAttributes on the action being executed. If we have a candidate then we call the ValidateAntiForgeryTokenAttribute class directly and execute OnAuthorization() on the current authorization context.

Now on our base controller, you could use this new attribute to start protecting your site from CSRF vulnerabilities.

[UseAntiForgeryTokenOnPostByDefault]
public class ApplicationController : System.Web.Mvc.Controller { }
 
//Then for all of your controllers
public class HomeController : ApplicationController {}

What we accomplished

If your base controller has the new default anti-forgery token attribute on it, when you don't use <%= Html.AntiForgeryToken() %> in a form (or of course when an attacker doesn't supply one), the POST action will throw the descriptive error message "A required anti-forgery token was not supplied or was invalid". Attack foiled!

In summary, I think having an anti-CSRF policy by default is an effective way to protect your websites, and it turns out it is pretty easy to accomplish as well.

Enjoy!

Filed under: , , , ,

Comments

# Twitter Trackbacks for Guarding against CSRF Attacks in ASP.NET MVC2 - Scott's Blog [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 Guarding against CSRF Attacks in ASP.NET MVC2 - Scott's Blog         [asp.net]        on Topsy.com

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Wednesday, April 14, 2010 10:15 PM by ASP.NET MvcPager

Nice article, thanks!

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Thursday, April 15, 2010 2:24 AM by Vladan Strigo

your only missing the Html.BeginForm which besides form also outputs by default the AntiForgeryToken....then you have the whole package!

Vladan

# Daily tech links for .net and related technologies - Apr 15-18, 2010

Thursday, April 15, 2010 5:42 AM by Sanjeev Agarwal

Daily tech links for .net and related technologies - Apr 15-18, 2010 Web Development Guarding against

# ASP.NET MVC Archived Blog Posts, Page 1

Sunday, April 18, 2010 11:52 PM by ASP.NET MVC Archived Blog Posts, Page 1

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Friday, April 23, 2010 3:49 AM by Mark Andrew

Good, simple and effective solutions for the problem.

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Friday, April 23, 2010 4:17 AM by Kacey Jone

nice post, really have informative information, thanks for publishing this post..

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Sunday, April 25, 2010 3:13 PM by Dave Kroondyk

To me, I see no reason for this. You still have to remember to put the <%= Html.AntiForgeryToken() %> in the form. I guess if you forget, you will get an error since it will check for it by default... but in this case, I'd rather have it automatically added to my form as well. Also, I think I'd rather see each action explicitly have the [ValidateAntiForgeryToken] attribute, just so I (or another developer) know what's going on. Less DRY? Sure. Easier to understand? Yes!

Adding the one extra attribute isn't enough to make me want to DRY it up. Even if it is on every POST. But, again, I'd rather have the option to just use it by default in the form and controller - this is how Rails works.

# Daily tech links for .net and related technologies &#8211; Apr 15-18, 2010 | OOP - Object Oriented Programing

Pingback from  Daily tech links for .net and related technologies &#8211; Apr 15-18, 2010 | OOP - Object Oriented Programing

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Wednesday, May 19, 2010 10:28 PM by Leo Rodriguez

Very nice article! Thanks a lot!

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Tuesday, June 01, 2010 2:57 AM by NEE

What about the ajax call? it doesn't work when i use the AntiForgeryTokenAttribute

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Sunday, August 08, 2010 1:39 PM by nam

also I have same problem with jquery ajax. need your help. thanks.

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Tuesday, August 24, 2010 6:39 AM by Mark little

nice post, really have informative information, thanks for publishing this post..

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Thursday, September 16, 2010 7:04 AM by Bayram

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Friday, November 05, 2010 12:50 AM by h miracle

With these types of problems arising nowadays, it's good to know that it is being taken cared of and hopefully, the solution will be very helpful in addressing the problem.

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Wednesday, February 16, 2011 1:32 AM by LaruzmRtvb

I imagine I could potentially think of this a variety of ways. Thanks for submitting it.

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Tuesday, March 08, 2011 4:06 PM by h miracle

I studied this post, but it is a little over my head. You must be one dude~!

# Get to Know Action Filters in ASP.NET MVC 3 Using HandleError

Thursday, March 17, 2011 1:32 PM by .net DEvHammer

What’s an Action Filter? If you’re just getting started with ASP.NET MVC , you may have heard of something

# Get to Know Action Filters in ASP.NET MVC 3 Using HandleError - MSDN Blogs

Pingback from  Get to Know Action Filters in ASP.NET MVC 3 Using HandleError - MSDN Blogs

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Saturday, May 14, 2011 6:46 PM by Emmitt

I think your idea of using of having an anti-CSRF policy by default is a sound one. I will look into implementing this on my sites. I hope it's as easy as you make it sound!

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Monday, June 27, 2011 2:49 AM by Dave S

Great example - thanks for that.

Just a suggestion, I would derive your class from the FilterAttribute and IAuthorizationFilter , and call your code from the OnAuthorization function instead of the OnActionExecuting  method.

That would avoid 'leaking' logic from the OnAuthorization event into the OnActionExecuting event

It will also give you an AuthorizationContext object from the engine, without having to emulate one.

# re: Guarding against CSRF Attacks in ASP.NET MVC2

Thursday, February 09, 2012 4:43 AM by Skizelucina

get <a href=www.dvdripper.org/>touchup dvd ripper</a>  for more detail

Leave a Comment

(required) 
(required) 
(optional)
(required)