Tuesday, September 29, 2015

Request Validation in ASP.NET

.NET Framework 4.5
Request validation is a feature in ASP.NET that examines an HTTP request and determines whether it contains potentially dangerous content. In this context, potentially dangerous content is any HTML markup or JavaScript code in the body, header, query string, or cookies of the request. 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.
For example, if your site has a form where users enter comments, a malicious user could enter JavaScript code in ascript element. When you display the comments page to other users, the browser executes the JavaScript code as if the code had been generated by your website. 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 throws this exception when any HTML markup is detected, including harmless markup like  (bold) elements. Throwing an error under this circumstance can be a problem if you want your application to accept HTML markup. For example, if your site lets users add comments, you might want to let users add basic formatting by using HTML tags that put text in bold or italics. In cases like these, you can disable request validation and check for malicious content manually. Or you can customize request validation so that certain kinds of markup or script are accepted. For information about how to customize request validation, see the whitepaper Security Extensibility in ASP.NET 4 (PDF). For information about how to specify a custom error page instead of the default error, page, see How to: Handle Application-Level Errors.
Security note Security Note
Even if you're using request validation, you should HTML-encode text that you get from users before you display it on a page. (Unless you've manually checked it for potentially malicious markup, as explained later.) For information about how to HTML-encode text, see the blog entry New <%: %> Syntax for HTML Encoding Output in ASP.NET 4 (and ASP.NET MVC 2) by Scott Guthrie.

Disabling Request Validation

Security note Security Note
If you disable request validation, you must check the user input yourself for dangerous HTML or JavaScript. For more information, see Manually Checking Requests later in this topic.
The method that you use to disable request validation depends on what type of ASP.NET web application you are working with:
  • ASP.NET Web Forms
  • ASP.NET MVC
  • ASP.NET Web Pages

Disabling Request Validation in ASP.NET Web Forms (ASP.NET 4 or later)

You can disable request validation for an entire application, but doing so is not recommended. The recommendation is to selectively disable request validation only for the virtual paths or specific pages where you want to allow markup.
In either case, you must make two changes in the Web.config file. The first change is to set therequestValidationMode attribute of the httpRuntime element to "2.0". This setting makes request validation occur later in the sequence of request processing events. The setting is required for applications that use ASP.NET 4 and later, because as of ASP.NET 4, request validation takes place earlier in the request life cycle than it did in previous versions of ASP.NET.

  

The following example shows how to make request validation occur later for a single page, in this case the Test.aspx page:

  
    
  

The second change is to set validationRequest to false. For the application as a whole, you do this using thepages element in the Web.config file as shown in the following example. (This setting is effective only if you also set requestValidationMode="2.0".)

  
    
  

For an individual page, you can set validationRequest to false in the @ Page directive of the page, as in the following example:
<@ Page validateRequest="false" %>

Disabling Request Validation in ASP.NET MVC

To disable request validation in an ASP.NET MVC application, you must change request validation to occur earlier in the sequence of request processing, as explained earlier for ASP.NET Web Forms. In the Web.config file, make the following setting:

  

In ASP.NET MVC, you can disable request validation for an action method, for a property, or for a field (input element) in a request. If you disable validation for an action method, you disable it for any requests that invoke that method—that is, all user input is allowed for any request that calls the action method. This approach is therefore the least secure way to disable request validation.
If you disable validation for a property, you allow user input for any reference to that property. If you disable validation for specific fields, you can control which request element (field) allows arbitrary user input.
To disable request validation for an action method, mark the method with the attribute ValidateInput(false), as shown in the following example:
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(string comment) 
{
    if (ModelState.IsValid) 
    {
        //  Etc.
    }
    return View(comment);
}
To disable request validation for a specific property, mark the property definition with the AllowHtml attribute:
[AllowHtml]
public string Prop1 { get;  set; }
To disable request validation for a specific field in a request (for example, for an input element or query string value), call the Request.Unvalidated method when you get the item, as shown in the following example:
var rawComment = Request.Unvalidated().Form["comment"];

Disabling Request Validation in ASP.NET Web Pages

To disable request validation for ASP.NET Web Pages, in code, call the Request.Unvalidated method and pass it the name of the field or other object that you want to bypass request validation for. The comments in the following code snippet indicate which lines of code trigger request validation and which ones do not.
Note Note
In ASP.NET Web Pages applications that do not also include Web Forms pages or MVC controllers, you do not have to change any settings in the Web.config file.
var userComment = Request.Form["userInput"]; // Validated, throws error if input includes markup

Request.Unvalidated("userInput"); // Validation bypassed
Request.Unvalidated().Form["userInput"]; // Validation bypassed

Request.QueryString["userPreference"]; // Validated
Request.Unvalidated().QueryString["userPreference"]; // Validation bypassed;

Manually Checking Requests

If you disable request validation, you must manually check the unvalidated user input for potentially dangerous input. Checking for dangerous input is critical for the security of your application. However, it is not necessarily an easy task. If your code is flawed or if you forget to protect one page or one field, malicious users might eventually find and exploit that weakness.
In general, you should restrict as narrowly as possible the list of HTML tags that you will accept, and reject everything else. (This approach is sometimes referred as using a safe terms list or a whitelist.)
If you are working with Web Forms pages, you can often use a third-party "rich text" control that lets users format text. These controls often have validation routines built in that permit only safe HTML. (If you use a control, make sure that it offers HTML safety.)
If you are not using a control, a simple approach is to HTML-encode the user input, and then to selectively unencode just the HTML tags that you want to allow. This approach is practical if the tags you want to allow do not include attributes, such as , and . The following example shows a way to encode and then selectively decode just the  and  tags.
// Encode the string input
StringBuilder sb = new StringBuilder(
    HttpUtility.HtmlEncode(htmlInputTxt.Text));
// Selectively allow  and 
sb.Replace("<b>", "");
sb.Replace("</b>", "
"); sb.Replace("<i>", ""); sb.Replace("</i>", "");
To allow more flexible HTML markup in the user input, you can use third-party libraries. Examples include the HTML Agility Pack that you can download from the CodePlex website and the open-source OWASP Anti-Samy utility. For more information, see the example on the OWASP site of disabling request validation for ASP.NET.
Another approach is to use an alternative form of markup, like MarkDown, and then convert the user's text to valid and safe HTML. Many wikis use this approach. For more information about Markdown, see the Daring Fireball site.

Additional Information


DataType Enumeration (MVC)

Represents an enumeration of the data types associated with data fields and parameters.
Namespace:   System.ComponentModel.DataAnnotations
Assembly:  System.ComponentModel.DataAnnotations (in System.ComponentModel.DataAnnotations.dll)

Syntax

public enum DataType

Members

Member nameDescription
CreditCard
Represents a credit card number.
Currency
Represents a currency value.
Custom
Represents a custom data type.
Date
Represents a date value.
DateTime
Represents an instant in time, expressed as a date and time of day.
Duration
Represents a continuous time during which an object exists.
EmailAddress
Represents an e-mail address.
Html
Represents an HTML file.
ImageUrl
Represents a URL to an image.
MultilineText
Represents multi-line text.
Password
Represent a password value.
PhoneNumber
Represents a phone number value.
PostalCode
Represents a postal code.
Text
Represents text that is displayed.
Time
Represents a time value.
Upload
Represents file upload data type.
Url
Represents a URL value.

Remarks

This enumeration is used to specify the type of data to associate with a data column or a parameter. You use theDataTypeAttribute class to specify the data type you want to associate with the data field or parameter. You select the data type from this enumeration.
The DataTypeAttribute attribute lets you mark fields by using a type that is more specific than the database intrinsic types. For example, a string data field that contains e-mail addresses can be attributed with the EmailAddress type. This information can be accessed by the field templates and modify how the data field is processed.
The following table lists the data types Dynamic Data provides.

Examples

The following example uses the DataTypeAttribute to customize the display of EmailAddress data field of the customer table in the AdventureWorksLT database. The e-mail addresses are shown as hyperlinks instead of the simple text that ASP.NET Dynamic Data would have inferred from the intrinsic data type.
The example code:
  • Implements a metadata partial class for the related table and the associated metadata class.
  • Applies the DataTypeAttribute attribute to the EmailAddress data field by specifying the EmailAddressenumerated value in the associated metadata class. This indicates to the Text.ascx field template that the e-mail address display is customized.
To compile the example code, you need the following:
  • Visual Studio 2008 Service Pack 1 or Visual Developer 2008 Express Edition Service Pack 1.
  • The AdventureWorksLT sample database. For information about how to download and install the SQL Server sample database, see Microsoft SQL Server Product Samples: Database on the CodePlex site. Make sure that you install the correct version of the sample database for the version of SQL Server that you are running (SQL Server 2005 or SQL Server 2008).
  • A Dynamic Data Web site. This enables you to create a data context for the database and the class that contains the data field to customize and the methods to override. In addition, it creates the environment in which to use the page described before. For more information, see Walkthrough: Creating a New Dynamic Data Web Site Using Scaffolding.
For the complete code example that the field template uses to customize the display of the EmailAddress data fields, see DataTypeAttribute.

Version Information

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 3.5
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 3.0

Friday, September 25, 2015

Using Filters (Pro ASP.NET MVC 5)

Introducing the Filter Types

The MVC Framework supports five different types of filters. Each allows you to introduce logic at different points during request processing. The filter types are described in Table 18-2.

Table 18-2: MVC Framework Filter Types
 Open table as spreadsheet
Filter Type
Interface
Default Implementation
Description
Authentication
IAuthenticationFilter
N/A
Runs first, before any other filters or the action method, but can be run again after the authorization filters
Authorization
IAuthorizationFilter
AuthorizeAttribute
Runs second, after authentication, but before any other filters or the action method
Action
IActionFilter
ActionFilterAttribute
Runs before and after the action method
Result
IResultFilter
ActionFilterAttribute
Runs before and after the action result is executed
Exception
IExceptionFilter
HandleErrorAttribute
Runs only if another filter, the action method, or the action result throws an exception


Before the MVC Framework invokes an action, it inspects the method definition to see if it has attributes that implement the interfaces listed in Table 18-2. If so, then at the appropriate point in the request handling process, the methods defined by these interfaces are invoked. The framework includes default attribute classes that implement the filter interfaces. 
Tip 
MVC 5 introduces a new interface, IoverrideFilter,

Filtering in ASP.NET MVC

In ASP.NET MVC, controllers define action methods that usually have a one-to-one relationship with possible user interactions, such as clicking a link or submitting a form. For example, when the user clicks a link, a request is routed to the designated controller, and the corresponding action method is called.
Sometimes you want to perform logic either before an action method is called or after an action method runs. To support this, ASP.NET MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods.
A Visual Studio project with source code is available to accompany this topic: Download.

ASP.NET MVC Filter Types

ASP.NET MVC supports the following types of action filters:
The Controller class implements each of the filter interfaces. You can implement any of the filters for a specific controller by overriding the controller's On method. For example, you can override the OnAuthorizationmethod. The simple controller included in the downloadable sample overrides each of the filters and writes out diagnostic information when each filter runs. You can implement the following On methods in a controller:

Filters Provided in ASP.NET MVC

ASP.NET MVC includes the following filters, which are implemented as attributes. The filters can be applied at the action method, controller, or application level.
  • AuthorizeAttribute. Restricts access by authentication and optionally authorization.
  • HandleErrorAttribute. Specifies how to handle an exception that is thrown by an action method.
    NoteNote:
    This filter does not catch exceptions unless the customErrors element is enabled in the Web.config file.
  • OutputCacheAttribute. Provides output caching.
  • RequireHttpsAttribute. Forces unsecured HTTP requests to be resent over HTTPS.

How To Create a Filter

You can create a filter in the following ways:
  • Override one or more of the controller's On methods.
  • Create an attribute class that derives from ActionFilterAttribute and apply the attribute to a controller or an action method.
  • Register a filter with the filter provider (the FilterProviders class).
  • Register a global filter using the GlobalFilterCollection class.
A filter can implement the abstract ActionFilterAttribute class. Some filters, such as AuthorizeAttribute, implement theFilterAttribute class directly. Authorization filters are always called before the action method runs and called before all other filter types. Other action filters, such as OutputCacheAttribute, implement the abstract ActionFilterAttributeclass, which enables the action filter to run either before or after the action method runs.
You can use the filter attribute declaratively with action methods or controllers. If the attribute marks a controller, the action filter applies to all action methods in that controller.
The following example shows the default implementation of the HomeController class. In the example, theHandleError attribute is used to mark the controller. Therefore, the filter applies to all action methods in the controller.
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}


Filter Providers

Multiple filter providers can be registered. Filter providers are registered using the static Providers property. TheGetFilters(ControllerContext, ActionDescriptor) method aggregates the filters from all of the providers into a single list. Providers can be registered in any order; the order they are registered has no impact on the order in which the filter run.
NoteNote:
Filter providers are a new feature to ASP.NET MVC 3.
By default, ASP.NET MVC registers the following filter providers:
The GetFilters method returns all of the IFilterProvider instances in the service locator.

Filter Order

Filters run in the following order:
  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters
For example, authorization filters run first and exception filters run last. Within each filter type, the Order value specifies the run order. Within each filter type and order, the Scope enumeration value specifies the order for filters. This enumeration defines the following filter scope values (in the order in which they run):
For example, an OnActionExecuting(ActionExecutingContext) filter that has the Order property set to zero and filter scope set to First runs before an action filter that has the Order property set to zero and filter scope set to Action. Because exception filters run in reverse order, an exception filter that has the Order property set to zero and filter scope set to First runs after an action filter that has the Order property set to zero and filter scope set to Action.
The execution order of filters that have the same type, order, and scope is undefined.
NoteNote:
In ASP.NET MVC version 3, the order of execution for exception filters has changed for exception filters that have the same Order value. In ASP.NET MVC 2 and earlier, exception filters on the controller with the same Order value as those on an action method were executed before the exception filters on the action method. This would typically be the case if exception filters are applied without a specified Order value. In ASP.NET MVC 3, this order has been reversed so that the most specific exception handler executes first. For more information, see the filter order section later in this document.

Canceling Filter Execution

You can cancel filter execution in the OnActionExecuting and OnResultExecuting methods by setting the Resultproperty to a non-null value. Any pending OnActionExecuted and OnActionExecuting filters will not be invoked and the invoker will not call the OnActionExecuted method for the canceled filter or for pending filters. TheOnActionExecuted filter for previously run filters will run. All of the OnResultExecutingand OnResultExecuted filters will run.
For example, imagine an ASP.NET MVC application that has a home controller and a simple controller. A global request timing filter is applied to the application. The request timing filter implements the four action and result filters (OnActionExecutingOnActionExecutedOnResultExecuting and OnResultExecuted). Each filter method in the application writes trace information with the name of the filter, the name of the controller, the name of the action and the type of the filter. In that case, the filter type is a request timing filter. A request to the Index action of the Homecontroller shows the following output in the trace listener (debug window).
Filter Method
Controller
Action
Filter type
OnActionExecuting
Home
Index
Request timing filter
OnActionExecuted
Home
Index
Request timing filter
OnResultExecuting
Home
Index
Request timing filter
OnResultExecuted
Home
Index
Request timing filter
Consider the same application where a trace action filter is applied to the simple controller. The simple controller also implements the four action and result filters. The simple controller has three filters, each of which implements the four action and result methods. A request to the Details action of the Simple controller shows the following output in the trace listener:
Filter Method
Controller
Action
Filter type
OnActionExecuting
Simple
Details
Simple Controller
OnActionExecuting
Simple
Details
Trace action
OnActionExecuting
Simple
Details
Request timing
OnActionExecuted
Simple
Details
Request timing
OnActionExecuted
Simple
Details
Trace action
OnActionExecuted
Simple
Details
Simple Controller
OnResultExecuting
Simple
Details
Simple Controller
OnResultExecuting
Simple
Details
Trace action
OnResultExecuting
Simple
Details
Request timing
OnResultExecuted
Simple
Details
Request timing
OnResultExecuted
Simple
Details
Trace action
OnResultExecuted
Simple
Details
Simple Controller
Now consider the same application where the trace action filter sets the result property to "Home/Index", as shown in the following example:
if (filterContext.RouteData.Values.ContainsValue("Cancel")) {
    filterContext.Result = new RedirectResult("~/Home/Index");
    Trace.WriteLine(" Redirecting from Simple filter to /Home/Index");
}
The request to the Details action of the Simple controller with the canceled result shows the following output in the trace listener:
Filter Method
Controller
Action
Filter type
OnActionExecuting
Simple
Details
Simple Controller
OnActionExecuting
Simple
Details
Trace action
OnActionExecuted
Simple
Details
Simple Controller
OnResultExecuting
Simple
Details
Simple Controller
OnResultExecuting
Simple
Details
Trace action
OnResultExecuting
Simple
Details
Request timing
OnResultExecuted
Simple
Details
Request timing
OnResultExecuted
Simple
Details
Trace action
OnResultExecuted
Simple
Details
Simple Controller
OnActionExecuting
Home
Index
Request timing filter
OnActionExecuted
Home
Index
Request timing filter
OnResultExecuting
Home
Index
Request timing filter
OnResultExecuted
Home
Index
Request timing filter
The downloadable sample for this topic implements the filtering described in these tables.

Filter State

Do not store filter state in a filter instance. Per-request state would typically be stored in the Items property. This collection is initialized to empty for every request and is disposed when the request completes. Transient per-user state is typically stored in the user's session. User-state information is often stored in a database. The downloadable sample for this topic includes a timing filter that uses per-request state. For information about how to create stateful filters, see the video Advanced MVC 3.

Related Topics

Title
Description
(Blog entry) Describes ASP.NET MVC filters in a service location context.
Describes how to use the Authorize attribute to control access to an action method.
Describes how to use the OutputCache attribute to provide output caching for an action method.
Describes how to use the HandleError attribute to handle exceptions that are thrown by an action method.
Describes how to implement custom action filters.
Explains how to add a custom action filter to an ASP.NET MVC application.