Prevent injection attacks in asp.net

Source: Internet
Author: User
Tags filter date format expression sql sql injection variable urlencode
Asp.net| attack

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 , 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 disable this feature by adding validaterequest= "false" to the element in your Web.config file or by setting validaterequest = "false" in the @pages element of a separate page.

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.

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

{

//
If validaterequest is false, then ' Hello ' is displayed

//
If ValidateRequest is true, then ASP.net returns a exception

Response.Write (Txtstring.text);
}


text= " "/>
text= "Submit"/>


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

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.


Controltovalidate= "Txtname"
validationexpression= "^[a-za-z '. \s]{1,40}$"
errormessage= "Invalid name" >

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:

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 #"%>

{
if (Request.requesttype = = "POST")

{
int i;
if (Int32.TryParse (request.f
orm["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");
}
}




Enter an integer between 0 and 255:
"



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 #"%>

{
DateTime DT;


//
Check for valid date and that the future

if (Datetime.tryparse (args). Value, out dt) = = False) | |
(dt <= Datetime.today))

{
Args. IsValid = false;
}
}




text= "Future Date:" >

Id= "CustomValidator1" runat= "Server"
Errormessage= "Invalid date. Enter a date in the future.
Controltovalidate= "Futuredatetxt"
Onservervalidate= "Validatedateinfuture" >







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 you to use and tags in order to display a simple text format.

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

{

//
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>", "");
Response.Write (sb.) ToString ());
}




Textmode= "MultiLine" width= "318px"
Height= "168px" >
text= "Submit"/>



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:

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. " The marks "replaced by <" (colons) are shown as harmless text.

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



Textmode= "MultiLine" width= "382px" height= "152px"

/>



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

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

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



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.