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. Detect and reject known harmful data 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. add validateRequest = "false" to the <pages> element in the config file or set ValidateRequest = "false" in the @ Pages element of the independent page 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 because the script in txtString is executed and processed by the client browser.
If you set ValidateRequest = "true" or remove the ValidateRequest page 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 server-side input verification. Do not rely on client-side verification because it is easy to bypass. Use client verification to reduce page return times and improve performance and 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. Specify the Integer or Double type for numeric input. Specify the String data type for character input. Specify the DateTime type for DateTime 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 must set the control name (ControlToValidate), validation expression (ValidationExpression), and error message (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 (RegularExpressionValidator) automatically adds the Escape Character (^) and dollar sign ($) as the separator for start and end. 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 (Regex class ).
Use regular expression class
Add a statement with the using prefix to import the System. Text. RegularExpressions namespace.
Make sure that the regular expression contains "^" and "$" (string start and string end ).
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, the input and range of numbers should be verified. use the Server Control to verify the input and range of numeric fields. Use the RangeValidator control. rangeValidator supports data of the currency, date, integer, double precision, and string type.
To use the RangeValidator control, you must set the ControlToValidate, Type, MinimumValue, MaximumValue, and error message attributes. 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 enter the value