Custom request validation in ASP.NET

ASP.NET request validation is ASP.NET’s built in way of saving our applications from dangerous script injection attacks or XSS attacks.The default validation provided by asp.net  is quite restrictive i.e. it doesn’t allow any html tag to be part of request.For more details on ASP.NET request validation go to this MSDN article.

Default request validation is good for simple application which does not deal with any HTML formatting but for a real world website this may not work.For example if you have an application where you allow user to input text with basic html formatting like bold or italic text or allow changing the color of the text ,the default validation will not allow this and you will see the familiar message.

A potentially dangerous Request.Form value was detected from the client.

To get around this problem we usually tend to disable the request validation which means we have to take care of all the input validation ourselves.

ASP.NET 4.0 provides another option to get around this problem by plugging your custom request validation logic.Lets see how we can do this.

For the purpose of this blog post I want to put a request validation logic which allows basic html formatting  and throws error if try to add some scripts as input.

Plugging your custom request validation

Below are the step required to plugin you custom request validation.

  • Request validation in ASP.NET is taken care by RequestValidator  class.To create our custom logic first step is to create a class which inherits form RequestValidator class.We will call this class HtmlRequestValidator.
public class HtmlRequestValidator : RequestValidator 
 { 
     public HtmlRequestValidator() {}
}
  • Next step is to override  IsValidRequestString method.This method is called on each of the value which asp.net wants to validate.
 protected override bool IsValidRequestString( HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex) 
    {

    }

Below is a brief explanation on what all the parameters to this method are :

  1. context : HttpContext instance of current request.
  2. value :  value which needs to be validated.
  3. requestValidationSource :   Enum describing what is the source of the value which is being validated e.g. Is this a cookie or Form value etc.
  4. collectionKey : In case the value is coming from a collection this key identifies the key of that collection e.g. if the value is from form collection then collectionKey would be the key of the value being validated.
  5. validationFailureIndex: This gives the index into the value string where dangerous value was detected.

For our purpose we will  just validate the values coming in form collection and call a method IsSafeHtml  which is suppose to return me boolean value indicating whether or not the value which is coming is a safe html.For all the other type of input like cookies ,files etc we will fall back to default request validation.

public class HtmlRequestValidator : RequestValidator 
 { 
     public HtmlRequestValidator() {}

   
        protected override bool IsValidRequestString( HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex) 
    {
        validationFailureIndex = -1; 
        
        if ( requestValidationSource == RequestValidationSource.Form   ) 
        {
            return IsSafeHtml(value,out validationFailureIndex);
        } 
        else 
        { 
            return base.IsValidRequestString( context, value, requestValidationSource, collectionKey, out validationFailureIndex); 
        } 
    }
	//Just a sample representative method
     bool IsSafeHtml(string s,out int outIndex)
     {
         outIndex = s.ToUpper().IndexOf("<SCRIPT");
         return outIndex == -1;
     }
 }

NOTE :

  1. IsSafeHtml method is just an example method to demonstrate the concept and by no means a foolproof method to safeguard against XSS attacks.For a production application you should consider using some of the Anti XSS libraries available.
  2. Another important point is that ASP.NET request validation is not triggered in case of AJAX based JSON POST requests like the one shown below.
$.ajax({
        url: '/Controller/Action',
        data: JSON.stringify({data:data}),
        type: "POST",
        dataType: "json",
        contentType: "application/json",
      }); 

So in these cases even if you have Request Validation enabled you should take care of validating such requests.

  • Last step in this whole process is to plug our custom validator.For this we need to add requestValidationType attribute in web.config file with fully qualified name of our custom validator.
<httpRuntime targetFramework="4.5" requestValidationType ="CustomValidationSample.HtmlRequestValidator">

That’s all.Lets see how it works.

Demo

I have created a simple form with few fields where I will first try to put some html text explicitly.

Add Html and Save

image

Saved without any request validation errors !!!

image

Lets try to create another entry by adding some scripts .

Add Script and Save

image

Error !!!

image

So our custom logic works.You can use this logic to validate not only form collection value but the values coming from cookes,files,headers etc.

In case you are interested in ASP.NET security in general , here is a very good pluralsight course (ASP.NET Security Secrets Revealed) that covers end to end every aspect of asp.net security.Also you can try book Beginning ASP.NET Security which is a good start for beginners.

Tagged on: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.