This site is the archived OWASP Foundation Wiki and is no longer accepting Account Requests.
To view the new OWASP Foundation website, please visit https://owasp.org

Difference between revisions of "ASP.NET Request Validation"

From OWASP
Jump to: navigation, search
(Description)
(Promoted)
 
(6 intermediate revisions by one other user not shown)
Line 1: Line 1:
= DRAFT DOCUMENT - WORK IN PROGRESS =
+
=Description=
 
 
==Description==
 
 
''Request validation'' is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. This exploit is typically referred to as a ''cross-site scripting'' (XSS) attack. Request validation helps to prevent this kind of attack by throwing a "potentially dangerous value was detected" error and halting page processing if it detects input that may be malicious, such as markup or code in the request.  
 
''Request validation'' is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. This exploit is typically referred to as a ''cross-site scripting'' (XSS) attack. Request validation helps to prevent this kind of attack by throwing a "potentially dangerous value was detected" error and halting page processing if it detects input that may be malicious, such as markup or code in the request.  
  
===Don't Rely on Request Validation for XSS Protection===
+
=Don't Rely on Request Validation for XSS Protection=
Request validation is generally desirable and should be left enabled for [[defense in depth]]. It should '''not''' be used as your sole method of XSS protection, and does not guarantee to catch every type of invalid input. There are known, documented bypasses (such as JSON requests) that will not be addressed in future releases, and the request validation feature is no longer supported in ASP.NET vNext.
+
Request validation is generally desirable and should be left enabled for [[defense in depth]]. It should '''NOT''' be used as your sole method of XSS protection, and does not guarantee to catch every type of invalid input. There are known, documented bypasses (such as JSON requests) that will not be addressed in future releases, and the request validation feature is no longer provided in ASP.NET vNext.
 
 
==Enabling Request Validation==
 
Request validation is enabled by default in ASP.NET. You can check to make sure it is not disabled at the page level by searching for any instances of:
 
  
<pre><@ Page ValidateRequest="false" %></pre>
+
Fully protecting your application from malicious input requires validating each field of user supplied data. This should start with [http://msdn.microsoft.com/en-us/library/debza5t0(v=vs.100).aspx ASP.NET Validation Controls] and/or [http://msdn.microsoft.com/en-us/library/ee256141(VS.100).aspx DataAnnotations attributes] to check for:
 +
* Required fields
 +
* Correct data type and length
 +
* Data falls within an acceptable range
 +
* Whitelist of allowed characters
  
You should also inspect the web.config file to ensure that request validation has not been disabled for the entire application:
+
Any string input that is returned to the client should be encoded using an appropriate method, such as those provided via [[ASP.NET Output Encoding#Enhanced_Encoding|AntiXssEncoder]].
  
<pre><pages validateRequest="false" /></pre>
+
<pre>var encodedInput = Server.HtmlEncode(userInput);</pre>
  
Starting with ASP.NET 4.0 request validation is performed for all requests, not just for .aspx page requests. To ensure this is configured correctly look to see that <code>requestValidationMode</code> has '''NOT''' been set to 2.0.
+
=Enabling Request Validation=
 +
Request validation is enabled by default in ASP.NET. You can check to make sure it is enabled by reviewing the following areas:
  
<pre><httpRuntime requestValidationMode="2.0" /></pre>
+
{| class="wikitable"
 +
|style="width: 20%;"|ASP.NET Web Forms (Global)
 +
|Ensure that request validation is set to true (or not set at all) in web.config: <pre><pages validateRequest="true" /></pre>
 +
|-
 +
|ASP.NET Web Forms (Page Level)
 +
|Check to make sure request validation is set to true (or not set at all) at the page level: <pre><@ Page ValidateRequest="false" %></pre>
 +
|-
 +
|ASP.NET 4.0+
 +
|Starting with ASP.NET 4.0 request validation is performed for all requests, not just for .aspx page requests. To ensure this is configured correctly requestValidationMode should be set to "4.0" (or not set at all) in web.config: <pre><httpRuntime requestValidationMode="4.0" /></pre>
 +
|-
 +
|ASP.NET 4.5+
 +
|There are enhancements added to request validation starting with ASP.NET 4.5 that include deferred ("lazy") validation, the ability to opt-out at the server control level, and the ability to access unvalidated data. In order to leverage these enhancements you will need to ensure that requestValidationMode has been set to "4.5" in web.config: <pre><httpRuntime requestValidationMode="4.5" targetFramework="4.5" /></pre>
 +
|-
 +
|ASP.NET Web API
 +
|ASP.NET Web API does not utilize the request validation feature to sanitize user input. You will need to add this protection manually if any input will be used in HTML output. For example if user input is returned to the browser as the result from an AJAX request to a Web API method.
 +
|}
  
===ASP.NET Web API===
+
=Selectively Disabling Request Validation=
ASP.NET Web API does not utilize the request validation feature to sanitize user input. You will need to add this protection manually if any input will be used in HTML output. For example if user input is returned to the browser as the result from an AJAX request to a Web API method.
+
In some cases you may need to accept input that will fail ASP.NET Request Validation, such as when receiving HTML markup from the end user. In these scenarios you should disable request validation for the smallest surface possible.
  
==Validating User Input==
+
==ASP.NET Web Forms==
Even though request validation provides a good level of input protection, you should not fully rely on it for securing your application against cross-site scripting attacks. Instead, validate all input from users to ensure malicious code is not included.
+
For ASP.NET Web Forms applications prior to v4.5, you will need to disable request validation at the page level. Be aware that when doing this all input values (cookies, query string, form elements) handled by this page will not be validated by ASP.NET.
 
+
<pre><@ Page ValidateRequest="false" %></pre>
Use <code>Server.HtmlEncode</code> to encode user input for use in HTML output:
 
<pre>var encodedHtmlInput = Server.HtmlEncode(userInput);</pre>
 
 
 
Use <code>Server.UrlEncode</code> to encode user input for use in constructing URLs
 
<pre>var encodedUrlInput = Server.UrlEncode(userInput);</pre>
 
 
 
===Enhanced Request Validation Encoding===
 
ASP.NET request validation uses a black-listing technique that evaluates the string for a set of character combinations that may indicate presence of malicious script. A superior approach is to use a [[Input Validation Cheat Sheet#White_List_Input_Validation|white-listing technique]] for input validation, which can be achieved using the Anti-Cross Site Scripting Library from Microsoft. Starting with ASP.NET 4.5 you can specify that the <code>AntiXssEncoder</code> from this library be used as the default encoder for you entire application using the <code>encoderType</code> setting in web.config as shown below.
 
<pre><httpRuntime encoderType="System.Web.Security.AntiXss.AntiXssEncoder" /></pre>
 
  
If you are using a version of .NET earlier than 4.5, you will need to download and include the library as a reference to your project, and then use the earlier library name for the encodeType setting as shown below.
+
Starting with ASP.NET 4.5 you can disable request validation at the individual server control level by setting <code>ValidateRequestMode</code> to "Disabled".
<pre><httpRuntime encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary" /></pre>
+
<pre><asp:TextBox ID="txtASPNet" ValidateRequestMode="Disabled" runat="server" /></pre>
  
==Selectively Disabling Request Validation==
+
==ASP.NET MVC==
In some cases you may need to accept input that will fail ASP.NET Request Validation, such as when receiving HTML markup from the end user. In these scenarios you should disable request validation for the smallest surface possible, and replace it with your own custom input validation.
 
 
 
===ASP.NET Web Forms===
 
For ASP.NET Web Forms applications you will need to disable request validation at the page level. Be aware that when doing this all input values (cookies, query string, form elements) handled by this page will not be validated by ASP.NET.
 
<pre><@ Page ValidateRequest="false" %></pre>
 
 
 
===ASP.NET MVC===
 
 
To disable request validation for a specific MVC controller action, you can use the <code>[ValidateInput(false)]</code> attribute as shown below.
 
To disable request validation for a specific MVC controller action, you can use the <code>[ValidateInput(false)]</code> attribute as shown below.
 
<pre>[ValidateInput(false)]
 
<pre>[ValidateInput(false)]
Line 63: Line 62:
 
}</pre>
 
}</pre>
  
==References==
+
=Extending Request Validation=
 +
If you are using ASP.NET 4.0 or higher, you have the option of extending or replacing the Request Validation logic by providing your own class that descends from <code>System.Web.Util.RequestValidator</code>. By implementing this class, you can determine when validation occurs and what type of request data to perform validation on.
 +
<pre>public class CustomRequestValidation : RequestValidator
 +
{
 +
    protected override bool IsValidRequestString(
 +
        HttpContext context,
 +
        string value,
 +
        RequestValidationSource requestValidationSource,
 +
        string collectionKey,
 +
        out int validationFailureIndex)
 +
    {
 +
        validationFailureIndex = -1;
 +
 
 +
        // This is just an example and should not
 +
        // be used for production code.
 +
        if (value.Contains("<%"))
 +
        {
 +
            return false;
 +
        }
 +
        else // Leave any further checks to ASP.NET.
 +
        {
 +
            return base.IsValidRequestString(
 +
                context,
 +
                value,
 +
                requestValidationSource,
 +
                collectionKey,
 +
                out validationFailureIndex);
 +
        }
 +
    }
 +
}</pre>
 +
This class is then registered in web.config using <code>requestValidationType</code>:
 +
<pre>
 +
<system.web>
 +
    <httpRuntime requestValidationType="CustomRequestValidation"/>
 +
</system.web>
 +
</pre>
 +
=References=
 
*[http://msdn.microsoft.com/en-us/library/hh882339(v=vs.110).aspx Request Validation in ASP.NET]
 
*[http://msdn.microsoft.com/en-us/library/hh882339(v=vs.110).aspx Request Validation in ASP.NET]
*[http://msdn.microsoft.com/en-us/library/System.Web.HttpUtility_methods(v=vs.110).aspx HttpUtility Methods]
+
*[http://msdn.microsoft.com/en-us/library/debza5t0(v=vs.100).aspx Validation ASP.NET Controls]
 +
*[http://msdn.microsoft.com/en-us/library/ee256141(VS.100).aspx How to: Validate Model Data Using DataAnnotations Attributes]
 +
*[http://msdn.microsoft.com/en-us/library/system.web.security.antixss.antixssencoder(v=vs.110).aspx AntiXssEncoder Class]
 +
*[http://www.asp.net/aspnet/overview/aspnet-and-visual-studio-2012/whats-new#_Toc318097379 New ASP.NET Request Validation Features]
 +
*[http://msdn.microsoft.com/en-us/library/system.web.ui.control.validaterequestmode(v=vs.110).aspx Control.ValidateRequestMode Property]
 
*[http://msdn.microsoft.com/en-us/library/system.web.mvc.validateinputattribute(v=vs.118).aspx ValidateInputAttribute Class]
 
*[http://msdn.microsoft.com/en-us/library/system.web.mvc.validateinputattribute(v=vs.118).aspx ValidateInputAttribute Class]
 
*[http://msdn.microsoft.com/en-us/library/system.web.mvc.allowhtmlattribute(v=vs.118).aspx AllowHtmlAttribute Class]
 
*[http://msdn.microsoft.com/en-us/library/system.web.mvc.allowhtmlattribute(v=vs.118).aspx AllowHtmlAttribute Class]
*[http://msdn.microsoft.com/en-us/library/system.web.security.antixss.antixssencoder(v=vs.110).aspx AntiXssEncoder Class]
+
*[http://msdn.microsoft.com/en-us/library/system.web.util.requestvalidator(v=vs.110).aspx RequestValidator Class]
*[http://www.microsoft.com/en-sg/download/details.aspx?id=43126 Microsoft Anti-Cross Site Scripting Library V4.3]
 
 
*[[ASP.NET Output Encoding]]
 
*[[ASP.NET Output Encoding]]
  
 
[[Category:OWASP .NET Project]]
 
[[Category:OWASP .NET Project]]

Latest revision as of 16:33, 26 November 2014

Description

Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. This check adds protection from markup or code in the URL query string, cookies, or posted form values that might have been added for malicious purposes. This exploit is typically referred to as a cross-site scripting (XSS) attack. Request validation helps to prevent this kind of attack by throwing a "potentially dangerous value was detected" error and halting page processing if it detects input that may be malicious, such as markup or code in the request.

Don't Rely on Request Validation for XSS Protection

Request validation is generally desirable and should be left enabled for defense in depth. It should NOT be used as your sole method of XSS protection, and does not guarantee to catch every type of invalid input. There are known, documented bypasses (such as JSON requests) that will not be addressed in future releases, and the request validation feature is no longer provided in ASP.NET vNext.

Fully protecting your application from malicious input requires validating each field of user supplied data. This should start with ASP.NET Validation Controls and/or DataAnnotations attributes to check for:

  • Required fields
  • Correct data type and length
  • Data falls within an acceptable range
  • Whitelist of allowed characters

Any string input that is returned to the client should be encoded using an appropriate method, such as those provided via AntiXssEncoder.

var encodedInput = Server.HtmlEncode(userInput);

Enabling Request Validation

Request validation is enabled by default in ASP.NET. You can check to make sure it is enabled by reviewing the following areas:

ASP.NET Web Forms (Global) Ensure that request validation is set to true (or not set at all) in web.config:
<pages validateRequest="true" />
ASP.NET Web Forms (Page Level) Check to make sure request validation is set to true (or not set at all) at the page level:
<@ Page ValidateRequest="false" %>
ASP.NET 4.0+ Starting with ASP.NET 4.0 request validation is performed for all requests, not just for .aspx page requests. To ensure this is configured correctly requestValidationMode should be set to "4.0" (or not set at all) in web.config:
<httpRuntime requestValidationMode="4.0" />
ASP.NET 4.5+ There are enhancements added to request validation starting with ASP.NET 4.5 that include deferred ("lazy") validation, the ability to opt-out at the server control level, and the ability to access unvalidated data. In order to leverage these enhancements you will need to ensure that requestValidationMode has been set to "4.5" in web.config:
<httpRuntime requestValidationMode="4.5" targetFramework="4.5" />
ASP.NET Web API ASP.NET Web API does not utilize the request validation feature to sanitize user input. You will need to add this protection manually if any input will be used in HTML output. For example if user input is returned to the browser as the result from an AJAX request to a Web API method.

Selectively Disabling Request Validation

In some cases you may need to accept input that will fail ASP.NET Request Validation, such as when receiving HTML markup from the end user. In these scenarios you should disable request validation for the smallest surface possible.

ASP.NET Web Forms

For ASP.NET Web Forms applications prior to v4.5, you will need to disable request validation at the page level. Be aware that when doing this all input values (cookies, query string, form elements) handled by this page will not be validated by ASP.NET.

<@ Page ValidateRequest="false" %>

Starting with ASP.NET 4.5 you can disable request validation at the individual server control level by setting ValidateRequestMode to "Disabled".

<asp:TextBox ID="txtASPNet" ValidateRequestMode="Disabled" runat="server" />

ASP.NET MVC

To disable request validation for a specific MVC controller action, you can use the [ValidateInput(false)] attribute as shown below.

[ValidateInput(false)]
public ActionResult Update(int userId, string description)

Starting with ASP.NET MVC 3 you should use the [AllowHtml] attribute to decorate specific fields on your view model classes where request validation should not be applied:

public class User 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    [AllowHtml]
    public string Description { get; set; }
    [AllowHtml]
    public string Bio { get; set; }
}

Extending Request Validation

If you are using ASP.NET 4.0 or higher, you have the option of extending or replacing the Request Validation logic by providing your own class that descends from System.Web.Util.RequestValidator. By implementing this class, you can determine when validation occurs and what type of request data to perform validation on.

public class CustomRequestValidation : RequestValidator
{
    protected override bool IsValidRequestString(
        HttpContext context, 
        string value, 
        RequestValidationSource requestValidationSource, 
        string collectionKey, 
        out int validationFailureIndex)
    {
        validationFailureIndex = -1;

        // This is just an example and should not
        // be used for production code.
        if (value.Contains("<%")) 
        {
            return false;
        }
        else // Leave any further checks to ASP.NET. 
        {
            return base.IsValidRequestString(
                context, 
                value, 
                requestValidationSource, 
                collectionKey, 
                out validationFailureIndex);
        }
    }
}

This class is then registered in web.config using requestValidationType:

<system.web>
    <httpRuntime requestValidationType="CustomRequestValidation"/>
</system.web>

References