How to Prevent injection attacks in. net

Source: Internet
Author: User

Purpose:

Restrict the length, range, format, and type of the input string.
In the development of ASP. NETProgramUse request verification to prevent injection attacks.
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 (XSS). XSS attacks use web page verification vulnerabilities to inject client scripts.CodeThe code is 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 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 int32.parse or convert. toint32 in the try/catch statement block and handle the formatexception error thrown when the conversion fails.

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. 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 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 the value to be within a specific range, you can use the range verification control (rangevalidator) set the allowed type to date. this control allows you to specify a special time period by setting the start time. you can use the customvalidator verification control to verify whether a time is in the future or in the past.

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 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. use httputility. the htmlencode method first encodes the input value.

Limited HTML code input allowed

Add the following field validaterequest = "false" to the @ page element to disable ASP. NET Request verification.
Use htmlencode to encode the input string
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. this page sets validaterequest = "fasle" to disable ASP.. NET Request verification. its HTML encoding allows <B> and <I> 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 (
Httputility. htmlencode (htmlinputtxt. Text ));

//
Selectively allow and <I>

SB. Replace ("& lt; B & gt;", "<B>"); www.mscto.com
SB. Replace ("& lt;/B & gt ;","");
SB. Replace ("& lt; I & gt;", "<I> ");
SB. Replace ("& lt;/I & gt ;","");
Response. Write (sb. tostring ());
}
</SCRIPT>
<HTML>
<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" onclick = "submitbtn_click"/>
</Div>
</Form>
</Body>
</Html>

Verify the query string value

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

Constraint input value
Set clear range check conditions
Specify the input type and convert it to ASP. the following code example shows how to use the RegEx class to verify the name string passed by the query string.

Void page_load (Object sender, eventargs E)

{
If (! System. Text. regularexpressions. RegEx. ismatch (
Request. querystring ["name"], @ "^ [A-Za-Z './S] {} $ "))
Response. Write ("invalid name parameter ");
Else
Response. Write ("name is" + request. querystring ["name"]);
}

Verify cookie value

Values stored in cookies like query strings are easily modified by users. The length, range, format, and type of these values are also verified.

Verify the file and URL

If your program allows you to enter a file name, file address, or file storage path, you need to verify that their format is correct and that it points to a valid location based on the actual situation of your program. if this step fails, your program may be incorrectly requested to access the file.

Verify file path

To prevent your program from being used by users to access files, and to prevent users from writing code input files or file paths. For example:

If you accept the input file name, use the system. Io. Path. getfilename method to obtain the full name of the file.
If you have to accept the input file path, use system. Io. Path. getfullpath to obtain the complete file path.

Use mappath to prevent cross-application ing

If you use the mappath method to map a provided virtual directory to a physical directory on the server, use request. an overloaded version of The mappath method with bool parameters to prevent cross-application ing. the following is a sample code for this technology:

Try

{
String mappedpath = request. mappath (inputpath. Text,
Request. applicationpath, false );
}
Catch (httpexception)

{

//
Cross-application mapping attempted

}

The final false parameter will prevent cross-application ing. This means that you are not allowed to use the syntax like "..." to provide an invalid path not in your specified virtual directory.

Software Development Network www.mscto.com

If you use the server control, you can use control. mappathsecure to obtain the actual directory address corresponding to the virtual directory.

The control. mappathsecure method throws an httpexception when accessing an unauthorized file. For more information, see control. mappathsecure In the. NET Framework document.

Use the code access security mechanism to restrict file input and output

The administrator can set the program to "medium" to restrict the program's ability to read and write files to its virtual directory .. net code security mechanism can ensure that the program does not have any file access rights outside its virtual directory.

To set the application's trust to "medium", you can add the following to the Web. config or machine. config file:

<Trust level = "medium"/>

Verify URL

You can use a regular expression like the following to perform URL feature matching.

^ (? : 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 only restricts the input format and does not verify whether it is within the acceptable range of the application. you should verify whether it is valid in the context of your program. for example, does your application communicate with the server you specified?

Step 3. encode Insecure code

If you enter text into a webpage, use httputility. htmlencode to encode it. If the text comes from user input, database, or a local file, make sure that this is always the case.

Similarly, if the URL you write contains insecure characters because they come from user input content, databases, and so on, use the httputility. urlencode Method for encoding.

To prevent the stored data from being corrupted by the Pre-encoding, make sure to encode the data as follows when displaying them.

Use htmlencode to encode insecure output

Htmlencode replaces HTML tags with special string containing texts to represent these symbols, and the browser does not interpret them as HTML tags. for example. "<" replaced with & lt; "(colon) with & quot; these labels 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>

<HTML xmlns = "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"
Onclick = "submitbtn_click"/>
</Div>
</Form>
</Body>
</Html>

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

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

If you remove the HTML code and enter the text content, the browser will execute the code and a prompt box will pop up.

Software Development Network www.mscto.com

Use urlencode to encode insecure URLs

If you need to obtain URL parameters that have been entered by users, this may pose a certain security risk. Use httputility. urlencode to encode the URL string.

Httputility. urlencode (urlstring );

Step 4. Use command parameters for SQL statements.

To avoid injection attacks, use the SQL parameter method. The parameter (parameters) Set provides the type detection and length detection. If you use the parameter set, the input content will beCompositionThe database does not execute the Code contained in the Code. an additional benefit of using the parameter set method is that you can strictly limit the type and length of the input. if the input type exceeds the specified range, an exception is triggered.

Use a parameter set when calling a stored procedure

The following code snippet demonstrates the 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 parameter set when creating your own SQL statement.

If you cannot use stored procedures, you can still use the parameter set. See the following code.

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 to prevent SQL injection attacks, see How to: protect from SQL Injection in ASP. NET.

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

You can use the <customerrors> element to configure the client. common error messages should be returned to the client by the program error detection mechanism.

Make sure that the mode attribute in Web. config has been changed to "remoteonly". The following is an example.

<Customerrors mode = "remoteonly">

After installing an ASP. NET program, you can set the client error page as follows.

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.