Preventing injection attacks in asp.net [translation]

Source: Internet
Author: User
Tags filter date expression how to prevent sql injection how to prevent sql injection attacks sql injection urlencode valid
Asp.net| attack

Source: MSDN
Translation: Cloud Midtown BLOG

Application scope:


asp.net vertion 1.1
asp.net vertion 2.0

Profile:

The text mainly describes how to validate user input to prevent injection attacks. Validating user input is essential, and almost all program-level attacks contain malicious input.

You should verify that include fields, query string parameters, cookies and all user entries to protect your program from injection attacks. You have to assume that all user input is malicious and that all user input is validated on the server side. Using client-based validation reduces the number of times a page is returned and improves performance, Improve the user experience, but not just rely on this, because client authentication can easily be fooled by hackers.

To validate the input, you should define acceptable input rules for each input field. A good practice is to constrain input from the length, range, format, and type of the input field. Use an acceptable character constraint list instead of an illegal character list to constrain the entry. Bad way to use illegal character list constraints, Because it's almost impossible for you to filter all the harmful inputs.

If you need to accept HTML character input, it's a good idea to encode it with HTMLEncode and so on to make sure it's safe to display.

Content:

Objective

Umbrella

Step-by-Step implementation of the Feed

First step. Use ASP.net to request checksums.

Step two. Use a constraint input for use.

Step three. Encodes unsafe input.

Fourth step. Use command parameter methods for SQL statements.

Fifth step. Verify that the ASP.net error has not been returned to the client.

Additional Resources


--------------------------------------------------------------------------------

Objective:

Constrain the length, range, format, and type of the input string.
Use request validation to prevent injection attacks when developing asp.net programs.
Use the ASP.net validation control for input validation.
Encode the unsafe output.
Use the command parameter set pattern to prevent injection attacks.
Prevents the details of the error from being returned to the client.
Overview:

You should validate all untrusted input in the program. You should assume that all user input is illegal. Users can provide form fields, query strings, client cookies and browser environment values such as user agent strings and IP addresses in the application.

Weak input checksums often provide an opportunity to inject an attack. The following are common means of attacking using weak input checksums or no input checksums.

SQL injection (SQL injection). If you use user input values to dynamically construct SQL statements, the database may execute offensive, unwanted SQL statements.
Cross-station scripting (Cross-site scripting). Cross-site scripting attacks inject client script with a Web page validation vulnerability. The code is then sent to the trusted client computer and interpreted by the browser. Because the code comes from a trusted site, the browser is not aware that the code is harmful.
Unlicensed file access (unauthorized file access). If your code accepts input from the caller, a malicious user can see how you are manipulating the file to access the protected files or use your code to inject the illegal data.

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

The usual input validation methods are summarized as follows. You should verify all the data you need to enter through the network, such as text boxes and other form input fields, query string parameters, cookies, server-side variables, and network method parameters. Note that The filtering policy should be to allow only the correct input and then reject the illegal input. This is because defining the correct input policy is easier than filtering all illegal input, which is often difficult to include all of the illegal input.

The following several aspects of the access to verify the input content:

Constraints. Verify that the correct type, character length, format, and range are entered. You can apply the ASP.net validation control to constrain server control input. Constraining input from other sources can use regular expressions and custom validation rules.
Reject. Detects known harmful data entry and rejects.
Filter. Sometimes you want to filter out those parts of your user input that have security implications. For example, your program allows free-form input, such as Memo fields, that you would allow for specific security HTML tags like <b>,<i> and other HTML tags.

Step Summary

Protect your ASP.net program against an injection attack by following these steps:

The first step. Use asp.net request validation.
Step two. Constraint input.
The third step is to encode the unsafe output.
Fourth step. Use command arguments for SQL query statements.
Fifth step. Verify that the asp.net error message is not leaked to the client.

These steps are discussed in detail in the following sections.

The first step. Use asp.net request validation.

By default, ASP.net 1.1 and 2.0 request authentication detects whether the data sent to the server contains HTML markup elements and reserved characters. This prevents users from entering scripts into the program. Request validation matches a list of potentially threatening strings. If an exception is found it throws a httprequestvalidationexception type of exception.

You can add validaterequest= "false" to the <pages> element in your Web.config file or set validaterequest = "false" in the @pages element of a separate page To disable this feature.

If you want to disable the request validation feature, you can disable it only on the page you want. For example, you include a field on the program page that accepts input from HTML format.

Determines that the request validation feature is turned on in the Machine.config file.

The request validation feature is enabled by default in asp.net. You can see the following default settings in the Machine.config.comments file.

<pages validaterequest = "true" .../>

Verify that you have not modified your server's machine.config and the default settings in the application's Web.config file.

Test asp.net request validation

You can test the role of request validation. Create a asp.net page by setting validaterequest = "Fasle" Disables request validation, the code is as follows:

<%@ language= "C #" validaterequest= "false"%>
 <script runat= "Server"
  void btnSubmit_Click (Object sender, EventArgs e)
  {
   //If validaterequest is False, Then ' Hello ' is displayed
   //If validaterequest are true, then ASP.net returns an exception
&NBSP ;   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"
                  text= "Submit"/>
  </FORM>
 </body

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

If you set validaterequest = "true" or remove ValidateRequest page properties, ASP. NET request validation rejects the script input and throws an error message such as the following.

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

Be careful not to rely solely on the request validation function, but only as a custom-validated coaching tool.

Step two. Constraint input

To constrain input through the following methods:

Use server-side input validation. Do not rely on client authentication because it is easily bypassed. Using client-side validation is to reduce the number of page returns to improve performance and improve the user experience.
Verify the length, range, format, and type of input. Make sure that the input is the correct content that meets the requirements.
Use a strong data type. Specifies a type such as Integer or double for input of a numeric type. Specifies a string data type for the character input. Specifies the datetime type for datetime input.
To verify the HTML control input fields inside the form, verify it in the server-side code, and use the Regex regular expression type to help constrain character input. The following section describes how to constrain a variable for a normal input type.

Validating a String field

To verify a string field, such as name, address, fax, certificate number, use regular expressions.
The range of acceptable characters for the constraint.
Start formatting rules. For example, a pattern based field such as tax number, ZIP code, postal code needs to specify the character pattern.
Verify the length.

Using regular expression validation controls (Regularexpresionvalidator)

To use an expression validation control you need to set the name of the control (ControlToValidate) to be validated, verify the expression (validationexpression), and error prompt (errormessage). Related property 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 code above, the regular expression is used to qualify the entered names as letters (allowing uppercase and lowercase letters), spaces, single-name ellipses like O ' Dell and periods. In addition, the length of the input character is limited to 40 characters.

Note the regular expression validation control (RegularExpressionValidator) automatically adds the caret (^) and dollar sign ($) As the start and end separator. If you don't join them in a custom expression then it's best to join them. Adding delimiters is just to get the part of the data that you want in your expression.

Use the Regular expression class (Regex Class)

If you don't use server-side controls (meaning you can't use validation controls), or if you need other input field sources rather than form fields (such as query string parameters and cookies), you can use regular expression classes (Regex Class).

Using Regular Expression Classes

Add a statement that uses a using prefix to import the System.Text.RegularExpressions namespace.
Confirm that the regular expression contains "^" and "$" (at the beginning of the string, at the end of the string).
Call the IsMatch method of the Regex class, and here is the code example.

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 against unnecessary object creation processes.

Verifying numeric fields

In most cases, you should verify the input and range of numbers. Use server controls to validate the input and range of numeric fields, using the RangeValidator control. RangeValidator supports currency, date, Integer, double, and string type data.

Use the RangeValidator control to set the control name (ControlToValidate) that needs to be validated, type (type), Minimum (MinimumValue), Maximum (MaximumValue), and error message (ErrorMessage) attribute. The following is a code example:

<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 don't use a server control, you can convert the input value to an integral type and validate it to complete the range validation of the number. For example, to verify that an integer is legitimate, use the new method provided by asp.net2.0 to int32.tryparse the input value into the System.Int32 variable type. This method returns False when the conversion fails.

Int32 i;
if (Int32.TryParse (Txtinput.text, out i) = = False)
{
Conversion failed
}

If you use the earlier version of ASP.net, you can use the Int32.Parse or Convert.ToInt32 method in the Try/catch statement block and handle the thrown FormatException error when the conversion fails.

The following example code demonstrates how to verify the type and scope of an integer type from an 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 a integer");
}
}

</script>

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

Validate Date Field

You need to verify that the Date field is the correct type. In most cases, you also need to verify their scope, such as verifying that they are in the future or in the past. If you use a server control to capture a date input value, and you want the value to be within a specific range, you can use the Scope validation control ( RangeValidator) and sets the type that it allows to be a date type. This control allows you to specify a specific time period by setting the starting point. If you need to use today's time as a reference to validation, such as verifying whether a time is in the future or the past, You can use the CustomValidator validation control.
Use the CustomValidator control to verify that a date requires setting the ControlToValidate and ErrorMessage properties and specifying a custom validation 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 future
if (Datetime.tryparse (args). Value, out dt) = = False) | |
(dt <= Datetime.today))
{
Args. IsValid = false;
}
}

</script>

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

Note The method used by the above code Datetime.tryparse is a new method provided by asp.net2.0.

Filter free text fields

Filter input, you need to make unsafe input not be treated as code. For example, your program uses users who cannot read data from a shared database, and you first need to filter the data to make it less dangerous to export. Use the Httputility.htmlencode method to encode the input value first.

Allow limited input HTML code

Field validaterequest = "false" in the @ Page element to disable asp.net request validation
To encode an input string using the HTMLEncode method
Use the StringBuilder object to replace the HTML in the character by calling its replace method
The following code gives an example of this approach. This page setup validaterequest = "Fasle" disables asp.net request validation. Its HTML encoding allows for the use of <b> and <i> tags in order to display a simple text format.

<%@ Page language= "C #" validaterequest= "false"%>

<script runat= "Server" >

  void SubmitBtn_Click (object sender, EventArgs e)
  {
   //Encode the string input    StringBuilder sb = new StringBuilder (
                              Httputility.htmlencode (Htmlinputtxt.text));
   //selectively allow  and <i>
    sb. Replace ("<b>", "<b>");
    sb. Replace ("</b>", "");
    sb. Replace ("<i>", "<i>");
    sb. Replace ("</i>", "");
    Response.Write (sb.) ToString ());
 }
</script>

<body>
<form id= "Form1" runat= "Server" >
<div>
<asp:textbox id= "Htmlinputtxt" runat= "Server"
Textmode= "MultiLine" width= "318px"
height= "168px" ></asp:TextBox>
<asp:button id= "submitbtn" runat= "Server"
text= "Submit"/>
</div>
</form>
</body>

Validating the value of a query string

Verify the length, range, format, and type of the query string. Typically, you use a combined regular expression to accomplish the following tasks:

Constraint input value


Set clear scope Check conditions
Specifies the type of input and converts it to a type under the ASP.net platform, handling any exceptions thrown by type conversions The following code example demonstrates using the Regex class to validate a name string passed over a query string

void Page_Load (object sender, EventArgs e)
{
if (! System.Text.RegularExpressions.Regex.IsMatch (
request.querystring["Name"], @ "^[a-za-z '. \s]{1,40}$"))
Response.Write ("Invalid name parameter");
Else
Response.Write ("name is" + request.querystring["name");
}

Verifying cookie values

The values stored in cookies like query strings are easily modified by the user. Similarly, verify the length, range, format, and type of these values.

Verifying file and URL addresses

If your program allows you to enter file names, file addresses, or file storage paths, you need to verify that they are in the correct format and point to a valid location based on your program's actual circumstances. If this step fails, your program may be incorrectly requesting access to the file.

Verifying file paths

To prevent your program from being used by users to access files, you are prevented from accepting files or file paths that users write code for. For example:

If you accept the input file name, use the System.IO.Path.GetFileName method to get the full name of the file
If you have to accept the input file path, use System.IO.Path.GetFullPath to get the full file path
Using the MapPath method to prevent cross application mapping

If you use the MapPath method to map a provided virtual directory to a physical directory on the server, use an overloaded version of the Request.mappath method with the bool parameter to prevent cross application mapping. The following is a sample code for this technique:

Try
{
String mappedpath = Request.mappath (Inputpath.text,
Request.applicationpath, false);
}
catch (HttpException)
{
Cross-application Mapping attempted
}

The final false parameter prevents mapping across applications. This means that users are not allowed to use the. "This syntax provides an illegal path that is not in the virtual directory you specify.

If you use a server control, you can use the Control.mappathsecure method to get the actual directory address of the virtual directory.
The Control.mappathsecure method throws an HttpException exception when accessing a file that is not authorized. For more information, refer to the Control.mappathsecure method introduction in the. NET Framework documentation.

Restricting file input and output with code access security

An administrator can restrict the ability of a program to read and write files to its virtual directory by setting up a program to make it "medium". NET code security to ensure that the program does not have any file access rights outside of the virtual directory in which it resides.

To set the trust of an application to medium, you can add in the Web.config or Machine.config file:

<trust level = "Medium"/>

Verifying URLs

You can match the URL with a regular expression like the one below.

^ (?: http|https|ftp)://[a-za-z0-9\.\-]+ (?: \:\ d{1,5})? (?: [a-za-z0-9\.\;\:\@\&\=\+\$\,\?/]|%u[0-9a-fa-f]{4}|%[0-9a-fa-f]{2}) *$

This is only the format of the constraint input and does not verify that it is within the scope acceptable to the application. You should verify that it works in the context of your program. For example, does your application communicate with the server you specify?

Step three. Encode unsafe code

If you enter text into a Web page, encode it using the Httputility.htmlencode method. If the text comes from user input, a database, or a local file, make sure you always do so.

Similarly, if you write URLs that contain unsafe characters because they come from user input, databases, and so on, they are encoded using the Httputility.urlencode method.

To prevent stored data from being corrupted before it can be stored, make sure that you encode them as soon as possible as they appear.

Using HTMLEncode to encode unsafe output

HTMLEncode the HTML markup into a special text-containing string to represent these symbols, and the browser does not interpret them as HTML tags. like. " < "replaced with <" (colon) are substituted with "These tags are displayed as harmless text."

<%@ Page language= "C #" validaterequest= "false"%>

<script runat= "Server" >
void SubmitBtn_Click (object sender, EventArgs e)
{
Response.Write (Httputility.htmlencode (Inputtxt.text));
}
</script>

http://www.w3.org/1999/xhtml" >
<body>
<form id= "Form1" runat= "Server" >
<div>
<asp:textbox id= "Inputtxt" runat= "Server"
Textmode= "MultiLine" width= "382px" height= "152px" >
</asp:TextBox>
<asp:button id= "submitbtn" runat= "Server" text= "Submit"
/>
</div>
</form>
</body>

To see the effect of HTML encoding, create a virtual directory to put the aforementioned files in, run this page, enter some HTML code in the text box, and click the Submit button. For example, the following input is displayed as plain text.

Run script and say hello <script>alert (' hello ');</script>

If you remove the call to the HTMLEncode method and simply enter the contents of the text, the browser executes the code and pops up a prompt box.

To encode an unsafe URL address using the UrlEncode method

If you need to obtain a URL parameter that has a user input part, this may pose a security risk, using the Httputility.urlencode method to encode the address string.

Httputility.urlencode (urlstring);

Fourth step. Use the command parameter method for the SQL statement.

To avoid injection attacks, use the SQL parameter method. The parameter (Parameters) collection provides type detection and length detection. If you use a parameter collection, the input is treated as a text value, and the database does not execute the code contained therein. An additional benefit of using the parameter set approach is that You can strictly limit the type and length of the input. If the input type is out of range, an exception will be triggered.

Use the set of parameters when calling a stored procedure

The following code fragment shows an example of using a parameter set when calling a stored procedure.

SqlDataAdapter mycommand = new SqlDataAdapter ("Authorlogin",
MyConnection);
MyCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parm = MYCOMMAND.SELECTCOMMAND.PARAMETERS.ADD (
"@LoginId", SqlDbType.VarChar, 11);
Parm. Value = Login.text;

Use the set of parameters when you create your own SQL statement.

If you can't use the stored procedure, you can still use the parameter set, see the code below.

SqlDataAdapter mycommand = new SqlDataAdapter (
"SELECT au_lname, au_fname from Authors WHERE au_id = @au_id", myconnection);
SqlParameter parm = MYCOMMAND.SELECTCOMMAND.PARAMETERS.ADD (
"@au_id", SqlDbType.VarChar, 11);
Parm.value = Login.text;

If you need more information on how to prevent SQL injection attacks, see how to To:protect from SQL injection in asp.net

Fifth step. Verify that the asp.net error message is not returned to the client

You can use the <customErrors> element to configure the client, and the general error message should be returned to the client by the program error detection mechanism.

Verify that the mode attribute in Web.config has been changed to "RemoteOnly", and here is an example.

<customerrors mode = "RemoteOnly" >

After installing a asp.net program, you can specify the client error message page as set below.

<customerrors mode = "on" defaultredirect = "yourerrorpage.htm" >

For additional resources, see Related Topics:

How to use regular expression constraint input in asp.net.

Preventing SQL injection attacks

Preventing cross-site scripting attacks

PS: Finally turned over Ah, really tired, spent nearly three days of time, in fact, look at these sentences are very simple. Please forgive me for the first time I have done translation.



Related Article

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.