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
(Page rewrite to capture advances in ASP.NET request validation)
Line 1: Line 1:
{{taggedDocument
+
= DRAFT DOCUMENT - WORK IN PROGRESS =
| type=partialOld
 
}}
 
  
ASP.NET Provides built-in request validation on form submission or postback handling. Request validation is on by default, and is handled differently by versions of the framework.  
+
==Description==
 +
''Request validation'' is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. ASP.NET performs this check because markup or code in the URL query string, cookies, or posted form values might have been added for malicious purposes. This exploit is typically referred to as a ''cross-site scripting'' (XSS) attack.
 +
Request validation helps prevent this kind of attack. If ASP.NET detects any markup or code in a request, it throws a "potentially dangerous value was detected" error and stops page processing. Request validation is generally desirable and should be left enabled unless you have a specific need that would prevent it from being used.
  
==ASP.NET 1.1 Request Validation Summary==
+
==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:
  
*Filter  "&#"
+
<pre><@ Page ValidateRequest="false" %></pre>
*Filter  ‘<’ then alphas or ! or / (tags)
 
*Filter  "script:"
 
*Filter  on handlers (onXXX=)
 
*Filter “expression(“
 
*Ignore elements named "__VIEWSTATE"
 
  
 +
You should also inspect the web.config file to ensure that request validation has not been disabled for the entire application:
  
==ASP.NET 2.0 Request Validation Summary==
+
<pre><pages validateRequest="false" /></pre>
  
*Filter  "&#"
+
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.
*Filter  ‘<’ then alphas or ! or / or ? (tags)
 
*Ignore elements with names prefixed with double underscore (__)
 
  
 +
<pre><httpRuntime requestValidationMode="2.0" /></pre>
  
==ValidateRequest Setting==
+
===ASP.NET Web API===
===To toggle request validation (it is set to true by default):===
+
ASP.NET Web API does not utilize the request validation feature to sanitize user input. You will need to add this protection manually if this 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.
  
On a single page:
+
==Validating User Input==
 +
Even though request validation provides a good level of input protection, do not fully rely on it for securing your application against cross-site scripting attacks. Instead, validate all input from users and encode the output to ensure malicious code is not included.
  
  <%@ Page validateRequest="true|false" %>
+
===Encoding Input Values in Code-Behind===
 +
Use <code>Server.HtmlEncode</code> to encode user input for use in HTML output:
 +
<pre>var encodedHtmlInput = Server.HtmlEncode(userInput);</pre>
  
For the entire application:
+
Use <code>Server.UrlEncode</code> to encode user input for use in constructing URLs
 +
<pre>var encodedUrlInput = Server.UrlEncode(userInput);</pre>
  
  <configuration>
+
Use <code>Server.UrlTokenEncode</code> to encode user input in byte array form for use as a URL parameter
    <system.web>
+
<pre>var encodedUrlTokenInput = Server.UrlTokenEncode(userInput);</pre>
          <pages validateRequest="true|false" />
 
    </system.web>
 
  </configuration>
 
  
===References===
+
===Encoding Output Values in HTML markup===
[http://phed.org/2008/04/23/aspnet-20-dumbs-down-request-validation/ ASP.NET 2.0 dumb’s down request validation (by Michael Eddington)]
+
You can HTML encode the value in markup with the <code><%: %></code> syntax, as shown below.
 +
<pre><span><%: userInput %></span></pre>
  
[http://keepitlocked.net/archive/2007/10/30/asp-net-validaterequest-and-the-html-attribute-based-cross-site-scripting.aspx ASP.NET ValidateRequest and the HTML Attribute Based Cross Site Scripting]
+
Or, in Razor syntax, you can HTML encode with <code>@</code>, as shown below.
 +
<pre><span>@userInput</span></pre>
 +
 
 +
===Preventing Double Encoding===
 +
You may run into a scenario where encoding values results in them becoming double encoded on output. ASP.NET provides the <code>HtmlString</code> and <code>MvcHtmlString</code> classes starting with .NET 4.0 which are designed to help. These both implement the <code>IHtmlString</code> interface which will instruct ASP.NET to not apply encoding within HTML markup when using <code><%: userInput %></code> or <code>@userInput</code>. Converting a property on your view model from <code>String</code> to <code>MvcHtmlString</code> will instruct ASP.NET that HTML encoding has already been accounted for.
 +
 
 +
===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.
 +
<pre><httpRuntime encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary" /></pre>
 +
 
 +
==Selectively Disabling Request Validation==
 +
In some cases you may need to accept input that will fail 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.
 +
<pre>[ValidateInput(false)]
 +
public ActionResult Update(int userId, string description) {</pre>
 +
 
 +
Starting with ASP.NET MVC 3 you should use the <code>[AllowHtml]</code> attribute to decorate specific fields on your view model classes where request validation should not be applied:
 +
<pre>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; }
 +
}</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/System.Web.HttpUtility_methods(v=vs.110).aspx HttpUtility Methods]
 +
*[http://weblogs.asp.net/scottgu/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2 New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2)]
 +
*[http://msdn.microsoft.com/en-us/library/system.web.ihtmlstring(v=vs.110).aspx IHtmlString Interface]
 +
*[http://stackoverflow.com/questions/2293357/what-is-an-mvchtmlstring-and-when-should-i-use-it What is an MvcHtmlString and when should I use it?]
 +
*[http://msdn.microsoft.com/en-us/library/system.web.security.antixss.antixssencoder(v=vs.110).aspx AntiXssEncoder Class]
 +
*[http://www.microsoft.com/en-sg/download/details.aspx?id=43126 Microsoft Anti-Cross Site Scripting Library V4.3]
 +
*[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]
  
 
[[Category:OWASP .NET Project]]
 
[[Category:OWASP .NET Project]]

Revision as of 21:40, 12 October 2014

DRAFT DOCUMENT - WORK IN PROGRESS

Description

Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content. ASP.NET performs this check because markup or code in the URL query string, cookies, or posted form values might have been added for malicious purposes. This exploit is typically referred to as a cross-site scripting (XSS) attack. Request validation helps prevent this kind of attack. If ASP.NET detects any markup or code in a request, it throws a "potentially dangerous value was detected" error and stops page processing. Request validation is generally desirable and should be left enabled unless you have a specific need that would prevent it from being used.

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:

<@ Page ValidateRequest="false" %>

You should also inspect the web.config file to ensure that request validation has not been disabled for the entire application:

<pages validateRequest="false" />

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 requestValidationMode has NOT been set to 2.0.

<httpRuntime requestValidationMode="2.0" />

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 this 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.

Validating User Input

Even though request validation provides a good level of input protection, do not fully rely on it for securing your application against cross-site scripting attacks. Instead, validate all input from users and encode the output to ensure malicious code is not included.

Encoding Input Values in Code-Behind

Use Server.HtmlEncode to encode user input for use in HTML output:

var encodedHtmlInput = Server.HtmlEncode(userInput);

Use Server.UrlEncode to encode user input for use in constructing URLs

var encodedUrlInput = Server.UrlEncode(userInput);

Use Server.UrlTokenEncode to encode user input in byte array form for use as a URL parameter

var encodedUrlTokenInput = Server.UrlTokenEncode(userInput);

Encoding Output Values in HTML markup

You can HTML encode the value in markup with the <%: %> syntax, as shown below.

<span><%: userInput %></span>

Or, in Razor syntax, you can HTML encode with @, as shown below.

<span>@userInput</span>

Preventing Double Encoding

You may run into a scenario where encoding values results in them becoming double encoded on output. ASP.NET provides the HtmlString and MvcHtmlString classes starting with .NET 4.0 which are designed to help. These both implement the IHtmlString interface which will instruct ASP.NET to not apply encoding within HTML markup when using <%: userInput %> or @userInput. Converting a property on your view model from String to MvcHtmlString will instruct ASP.NET that HTML encoding has already been accounted for.

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 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 AntiXssEncoder from this library be used as the default encoder for you entire application using the encoderType setting in web.config as shown below.

<httpRuntime encoderType="System.Web.Security.AntiXss.AntiXssEncoder" />

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.

<httpRuntime encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary" />

Selectively Disabling Request Validation

In some cases you may need to accept input that will fail 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.

<@ Page ValidateRequest="false" %>

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; }
}

References