ASP.NET 2.0 Security Practices - Input and Data Validation

From Guidance Share

Jump to: navigation, search

Contents

How to validate input in ASP.NET

Assume all input is malicious. To validate input, define acceptable input for your fields. Constrain input for length, range, format, and type. Use an "allow" approach up front and define what constitutes valid input instead of relying on "deny" approaches. The problem with a "deny" approach is that it is very difficult to anticipate all possible variations of bad input. Do not rely on client-side validation as your only input validation mechanism because it can be easily bypassed. Use client-side validation only to reduce round trips and to improve the user experience. For more information, see How To: Protect From Injection Attacks in ASP.NET.


How to validate input in server controls

Validate input from server controls by using the ASP.NET validation controls, such as the RangeValidator, RequiredFieldValidator, CustomValidator, or RegularExpressionValidator. The following example shows a RegularExpressionValidator control that has been used to validate a name field.

<form id="WebForm" method="post" runat="server">
  <asp:TextBox id="txtName" runat="server"></asp:TextBox>
  <asp:RegularExpressionValidator id="nameRegex" runat="server" 
        ControlToValidate="txtName" 
        ValidationExpression="^[a-zA-Z'.\s]{1,40}$" 
        ErrorMessage="Invalid name">
  </asp:regularexpressionvalidator>
</form>

The validation controls use client-side script to perform validation on the client browser (if supported by the browser), and also run validation logic on the server after data is posted back.


How to validate input in HTML controls, QueryString, cookies, and HTTP headers

Use the System.Text.RegularExpression.Regex class to validate this type of input to verify that the input matches an expected format, as shown in the following example.

// Static method:
if (!Regex.IsMatch(Request.QueryString.Get("Number"), 
                   @"\d{3}-\d{2}-\d{4}")) 
{
  // Invalid Social Security Number
}

For more information, see How To: Use Regular Expressions to Constrain Input in ASP.NET.


How to prevent cross site scripting

Validate input and encode output. Constrain input by validating it for type, length, format, and range. Use the HttpUtility.HtmlEncode method to encode output if it contains input from the user, such as input from form fields, query strings, and cookies or from other sources, such as databases. Never just echo input back to the user without validating and/or encoding the data. The following example shows how to encode a form field.

Response.Write(HttpUtility.HtmlEncode(Request.Form["name"]));


If you return URL strings that contain input to the client, use the HttpUtility.UrlEncode method to encode these URL strings, as shown here.

Response.Write(HttpUtility.UrlEncode(urlString));


If you have pages that need to accept a range of HTML elements, such as through some kind of rich text input field, you must disable ASP.NET request validation for the page.


To safely allow restricted HTML input:

  1. Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @ Page directive.
  2. Encode the string input with the HtmlEncode method.
  3. Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit as shown here.
    ...
    // Encode the string input from the HTML input text field
    StringBuilder sb = new StringBuilder(HttpUtility.HtmlEncode(htmlInputTxt.Text));
    // Selectively allow <b> and <i>
    sb.Replace("<b>", "<b>");
    sb.Replace("</b>", "</b>");
    sb.Replace("<i>", "<i>");
    sb.Replace("</i>", "</i>");
    


For more information, see How To: Prevent Cross-Site Scripting in ASP.NET.

Personal tools