Preventing injection attacks in ASP. NET [translation] preventing injection attacks in ASP. NET [translation]

Source: Internet
Author: User
Preventing injection attacks in ASP. NET [translation]

Source: MSDN original address

Application Scope:

 

  • ASP. NET vertion 1.1
  • ASP. NET vertion 2.0

     

    Summary:

    This document describes how to verify user input to prevent injection attacks. It is essential to verify user input. Almost all program-level attacks include malicious input methods.

    You should verify all user input items including fields, query string parameters, and cookies to protect your program from injection attacks. assume that all user input is malicious, so make sure that all user input is verified on the server side. client-based verification can reduce the number of page visits, improve performance, and improve user experience, but it is not solely dependent on this because client verification can easily be cheated by hackers.

    To verify the input content, you should define an acceptable input rule for each input field. it is better to constrain the length, range, format, and type of input fields. use an acceptable character constraint list instead of an invalid character list to constrain input. the use of invalid character list constraints is not good because you can hardly filter all harmful input.

    If you need to accept HTML characters, it is best to use methods such as HtmlEncode to encode them to ensure security and display them.

    Content:

    Purpose

    Summary

    Step-by-step implementation Overview

    Step 1. use ASP. NET for request validation.

    Step 2. constraint input for use right.

    Step 3. encode insecure input.

    Step 4. Use command parameters for SQL statements.

    Step 5. Verify that ASP. NET errors are not returned to the client.

    Additional resources

    Purpose:

     

  • Restrict the length, range, format, and type of the input string.
  • Use request verification to prevent injection attacks when developing ASP. NET programs.
  • Use the ASP. NET verification control for input verification.
  • Encode insecure output.
  • Use the command parameter set mode to prevent injection attacks.
  • Prevent detailed error information from being returned to the client.

    Overview:

    You should verify all untrusted input in the program. assume that all user input is invalid. you can provide form fields, query strings, client cookies, and browser Environment Values in applications, such as user proxy strings and IP addresses.

    The weak Input Validation usually provides an opportunity for injection attacks. The following are common methods to use the weak input validation or the non-Input Validation for attacks.

     

  • SQL injection ).If you use user input values to dynamically construct SQL statements, the database may execute malicious and harmful SQL statements.
  • Cross-site scripting ).Cross-site scripting (XSS) attacks inject client scripts by exploiting the web page verification vulnerability. the code is then sent to a trusted client computer and interpreted and executed by the browser. because the Code comes from a trusted site, the browser cannot know that the code is harmful.
  • Unauthorized file access (Unauthorized file access ).If your code receives input from the caller, malicious users can view the file operation process to access the protected files or inject illegal data using your code.

     

    Note: injection attacks can be connected by using HTTP or HTTPS Secure Socket Layer (SSL). Transmission encryption technology cannot be used to defend against attacks.

    The input verification method is summarized as follows. you should verify all fields that need to be input over the network, such as text boxes and other form input fields, query string parameters, cookies, server variables, and network method parameters. note that the filter policy should only allow correct input and then reject illegal input. this is because it is easier to define a correct input policy than to filter all illegal inputs. It is usually difficult to include all illegal inputs.

    Verify the input in the following ways:

     

  • Constraint.Verify whether the input is of the correct type, character length, format, and range. ASP.. NET verification control to constrain the input of the server control. to restrict input from other sources, you can use regular expressions and custom verification rules.
  • Reject.Detects known harmful data input and rejects the input.
  • Filter.Sometimes you want to filter out the security risks in user input. for example, if your program allows input in a free format, such as a remarks field, you can allow specific security HTML tags such as <B>, <I>, and other HTML tags.

     

    Step 1

    Follow these steps to protect your ASP. NET programs from injection attacks:

     

  • Step 1. use ASP. NET for request verification.
  • Step 2. constraint input.
  • Step 3. encode insecure output.
  • Step 4. Use command parameters for SQL query statements.
  • Step 5. Verify that the error information of ASP. NET is not leaked to the client.

     

    The following sections describe these steps in detail.

    Step 1. use ASP. NET for request verification.

    By default, ASP. NET 1.1 and 2.0 request verification checks whether the data sent to the server contains HTML Tag elements and reserved characters. this prevents the user from entering scripts into the program. request verification matches a list of strings with potential threats. if an exception is found, an HttpRequestValidationException type exception is thrown.

    You can<Pages>Add to elementValidateRequest = "false"Or on a separate page@ PagesSet in the elementValidateRequest = "false"To disable this function.

    If you want to disable the request verification function, you can only disable it on the required page. For example, you include a field that can be entered in HTML format on the program page.

    Make sure the request verification function is enabled in the Machine. config file.

    The request verification function is enabled by default in ASP. NET. You can see the following default settings in the Machine. config. comments file.

    <Pages validateRequest = "true".../>

    Make sure that you have not modified the default settings in the Machine. config file of your server and the Web. config file of the application.

    Test ASP. NET Request Verification

    You can test the role of request verification. Create an ASP. NET page to disable request verification by setting ValidateRequest = "fasle". The Code is as follows:

     

    <% @ Language = "C #" ValidateRequest = "false" %>
    <Html>
    <Script runat = "server">
    Void btnSubmit_Click (Object sender, EventArgs e)
    {
    // If ValidateRequest is false, then 'Hello' is displayed
    // If ValidateRequest is true, then ASP. NET returns an exception
    Response. Write (txtString. Text );
    }
    </Script>
    <Body>
    <Form id = "form1" runat = "server">
    <Asp: TextBox id = "txtString" runat = "server"
    Text = "<script> alert ('hello'); </script>"/>
    <Asp: Button id = "btnSubmit" runat = "server" OnClick = "btnSubmit_Click"
    Text = "Submit"/>
    </Form>
    </Body>
    </Html>

     

    When you run the page, "Hello" is displayed in a message box, becauseTxtStringThe script is executed and processed by the client browser.

    If you setValidateRequest = "true"Or removeValidateRequestPage attribute. ASP. NET Request validation rejects script input and throws an error message like the following.

     

    A potentially dangerous Request. Form value was detected from the client (txtString = "<script> alert ('Hello ").

     

    Be sure not to rely solely on the request verification function, but to use it as a tutoring Method for custom verification.

    Step 2. constraint Input

    To constrain the input, use the following method:

     

  • Use the Server Input for verification.Do not rely on client verification because it is easily bypassed. Client verification is used to reduce the number of page return times to improve performance and improve user experience.
  • Verify the length, range, format, and type of the input.Make sure that the entered content is correct.
  • Use a strong data type.It is a numeric input, such as Integer or Double type. It is a String data type for character input. It is a DateTime type for date and time input.

    To verify the HTML control input field in the form, verify it in the server code. The Regex regular expression type can help constrain character input. the following section describes how to constrain variables of the common input type.

    Verify string Fields

     

  • To verify the string field, such as name, address, fax, and certificate number, use a regular expression.
  • Limits acceptable character ranges.
  • Start format rules. For example, the pattern-based fields such as tax ID, zip code, and postal code must specify the character pattern.
  • Verification length.

     

    Use a regular expression to verify the control (RegularExpresionValidator)

    To use the expression to verify the control, you need to set the name of the control to be verified (ControlToValidate), Verify the expression (ValidationExpressionAnd error messages (ErrorMessage). For more information about attribute settings, see the following code example.

     

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

     

    In the above Code, regular expressions are used to limit the input name to letters (uppercase and lowercase letters are allowed), spaces, and single-name ellipsis like o'dell and periods. in addition, the length of the input characters is limited to 40 characters.

    Note that the regular expression verification control (RegularExpressionValidatorThe delimiters (^) and dollar signs ($) are automatically added as the start and end separators. if you haven't added them to a custom expression, you 'd better add them. the separator is added only to get the desired data content for your expression.

    Use a regular expression Class (Regex Class)

    If you do not use a server-side control (which means you cannot use a verification control), or you need other input field sources rather than form fields (such as querying string parameters and cookies ), then you can use the regular expression class (RegexClass ).

    Use regular expression class

    1. Add a statement with the using prefix to import the System. Text. RegularExpressions namespace.
    2. Make sure that the regular expression contains "^" and "$" (string start and string end ).
    3. Call the IsMatch method of the Regex class. The following is a sample code.

     

    // Instance method:
    Regex reg = new Regex (@ "^ [a-zA-Z '. \ s] {1, 40} $ ");
    Response. Write (reg. IsMatch (txtName. Text ));

    // Static method:
    If (! Regex. IsMatch (txtName. Text, @ "^ [a-zA-Z '. \ s] {1, 40} $ "))
    {
    // Name does not match expression
    }

     

    If you cannot cache frequently used regular expressions, you should use the IsMatch static method to improve performance and prevent unnecessary object creation processes.

    Verify Numeric Fields

    In most cases, you should verify the number input and range. Use the Server Control to verify the number field input and range, useRangeValidatorControl.RangeValidatorData of the currency, date, integer, double precision, and string type is supported.

    To use the RangeValidator control, you must set the name of the control to be verified (ControlToValidate), Type (Type), Minimum value (MinimumValue), Maximum value (MaximumValue), And error message (ErrorMessage) Properties. The following is a sample code:

     

    <Asp: RangeValidator
    ID = "RangeValidator1"
    Runat = "server"
    ErrorMessage = "Invalid range. Number must be between 0 and 255 ."
    ControlToValidate = "rangeInput"
    MaximumValue = "255"
    MinimumValue = "0" Type = "Integer"/>

     

    If you do not use the server control, you can convert the input value to an integer and then verify the range of the number. for example, to verify whether an integer is valid, use ASP. the new method Int32.TryParse provided by NET2.0 converts the input value to System. variable type of Int32. this method returns false if the conversion fails.

     

    Int32 I;
    If (Int32.TryParse (txtInput. Text, out I) = false)
    {
    // Conversion failed
    }

     

    If you use an earlier ASP. NET version, you can use it in the try/catch statement block.Int32.ParseOrConvert. ToInt32Method.FormatExceptionError.

    The following sample code demonstrates how to verify the type and range of the integer type from the HTML text box.

     

    <% @ Page Language = "C #" %>

    <Script runat = "server">

    Void Page_Load (object sender, EventArgs e)
    {
    If (Request. RequestType = "POST ")
    {
    Int I;
    If (Int32.TryParse (Request. Form ["integerTxt"], out I) = true)
    {
    // TryParse returns true if the conversion succeeds
    If (0 <= I & I <= 255) = true)
    {
    Response. Write ("Input data is valid .");
    }
    Else
    Response. Write ("Input data is out of range ");
    }
    Else
    Response. Write ("Input data is not an integer ");
    }
    }

    </Script>

    <Html>
    <Body>
    <Form id = "form1" action = "NumericInput. aspx" method = "post">
    <Div>
    Enter an integer between 0 and 255:
    <Input name = "integerTxt" type = "text"/>
    <Input name = "Submit" type = "submit" value = "submit"/>
    </Div>
    </Form>
    </Body>
    </Html>

     

    Verification Date Field

    Verify that the date field is of the correct type. in most cases, you also need to verify their scope, such as whether they are future or past time. if you use the Server Control to capture a Date input value and want this value to be within a specific range, you can use the range verification control (RangeValidator) And set the allowed typeDateType. this control allows you to specify a special time period by setting the start time. you can useCustomValidatorVerify the control.

    To use the CustomValidator control to verify a date, you must set the ControlToValidate and ErrorMessage attributes, and specify a custom authentication logic method in the OnServerValidate event. The following is the sample code.

     

    <% @ Page Language = "C #" %>

    <Script runat = "server">

    Void ValidateDateInFuture (object source, ServerValidateEventArgs args)
    {
    DateTime dt;

    // Check for valid date and that the date is in the future
    If (DateTime. TryParse (args. Value, out dt) = false) |
    (Dt <= DateTime. Today ))
    {
    Args. IsValid = false;
    }
    }

    </Script>

    <Html>
    <Body>
    <Form id = "form1" runat = "server">
    <Div>
    <Asp: Label ID = "Label1" Runat = "server"
    Text = "Future Date:"> </asp: Label>
    <Asp: TextBox ID = "futureDatetxt" Runat = "server"> </asp: TextBox>
    <Asp: CustomValidator
    ID = "CustomValidator1" Runat = "server"
    ErrorMessage = "Invalid date. Enter a date in the future ."
    ControlToValidate = "futureDatetxt"
    OnServerValidate = "ValidateDateInFuture">
    </Asp: CustomValidator>
    <Br/>
    <Asp: Button ID = "submitBtn" Runat = "server" Text = "Submit"/>
    </Div>
    </Form>
    </Body>
    </Html>

     

    Note that the method DateTime. TryParse used in the above Code is a new method provided by ASP. NET2.0.

    Filter free text fields

    Filter input. You need to prevent insecure input from being treated as code. for example, if your program prevents users from reading data from the shared database, you must first filter the data so that it is not dangerous to output the data. useHttpUtility. HtmlEncodeEncode the input value.

    Limited HTML code input allowed

     

    1. Add the following field ValidateRequest = "false" to the @ Page element to disable ASP. NET Request verification.
    2. Use HtmlEncode to encode the input string
    3. Use the StringBuilder object to call its Replace method to Replace the HTML in the character

    The following code provides an example of this method.ValidateRequest = "fasle"ASP. NET Request verification is disabled. Its HTML encoding allows the use of <B> and <I> flag to display simple text formats.

     

    <% @ Page Language = "C #" ValidateRequest = "false" %>

    <Script runat = "server">

    Void submitBtn_Click (object sender, EventArgs e)
    {
    // Encode the string input
    StringBuilder sb = new StringBuilder (
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.