Asp.net prevents SQL statement Injection

Source: Internet
Author: User
Tags sql injection attack net domain

1. SQL injection is difficult to defend against. A dozen characters, such as select and delete, must be replaced.

It turns out that it is better to replace the single quotation marks with two single quotation marks when dealing with character-type replacement! It is not effective to deal with digital replacement. Category conversion is required.

2. Neglected tools from DropDownList

It turns out to be a fault. All customers believe it in their real tools, and so is the select drop-down box! You can create an htm and submit it to the worker.

3. access is better than SQL Server

Ann is worried about how to use it. If SQL Server is still used like access and has a sa account, it is clear that SQL Server is more worried than access, and you can directly get the table name and field name! Access is better, because it can only be resolved by bit.

4. Clarify that the website is well-formed without showing any false information

When there is a recorded time show records, there is no recording of the time show can not find any records, the two States can be resolved to guess the field name, so the web page is not enough to clarify is safe

5. Neglected post submitted information

Many people strictly filter the tools conveyed on the url. It is a fault to ignore the tools used to deal with post. The tools used for post are especially double and simple to be injected, because the common fields have a lot of corner power.

In asp.net, we strongly recommend parameter determination to implement SQL rather than SQL concatenation, because even if you filter hundreds of passwords

Qi:

SqlConnection conn = new SqlConnection (System. Configuration. ConfigurationSe ttings. deleettings ["conn"]);

SqlCommand comm = new SqlCommand ("update tb1 set vName = @ vName, iAge = @ iAge where ID = @ id", conn );

SqlParameter parm1 = new SqlParameter ("@ vName", SqlDbType. NVarChar, 50 );

Parm1.Value = (TextBox) e. Item. FindControl ("name"). Text;

SqlParameter parm2 = new SqlParameter ("@ iAge", SqlDbType. Int );

Parm2.Value = (TextBox) e. Item. FindControl ("age"). T ext;

SqlParameter parm3 = new SqlParameter ("@ id", SqlDbType. Int );

Parm3.Value = this. DataGrid1.DataKeys [e. Item. ItemInd ex];

Comm. Parameters. Add (parm1 );

Comm. Parameters. Add (parm2 );

Comm. Parameters. Add (parm3 );

Conn. Open ();

Comm. ExecuteNonQuery ();

Conn. Close ();

This code looks comfortable and safe. Why? [Guide] This article introduces five common ASP. NET application steps to improve the security of defects

1. Do not blindly trust user input

In Web application development, the biggest mistake of the pioneer is often unconditional trust in user input. It is assumed that the user (even malicious users) is always limited by the reader and always decides the interaction between the reader and the worker, this opens the door to attack Web applications. In reality, hackers attack and manipulate many Web site devices without having to focus on the reader, from the original interface (such as telnet) with the lowest level of character mode ), to CGI script scanners, Web agents, and Web application scanners, there are many attack modes and methods adopted by malicious users.

Therefore, only strict validation of the legitimacy of user input can effectively resist hacker attacks. The application steps can be verified by multiple essentials (or even those with overlapping verification scopes). For example, the verification is performed before the user input is acknowledged to ensure that the user input contains only valid characters, and the content length of all input fields is not beyond the scope (to guard against or appear in the buffer overflow attack). In this case, other verification is performed to ensure that the user input data is not only valid, but also fair. Need not only can select forced length limit strategy, but also to input content in accordance with the definition of the feature set for verification. The following initiatives will help you verify user input data correctly:

(1) Verification is always performed on all user input. verification must be performed on a reliable platform and on multiple layers of the application.

(2) do not permit any content except the data required for input and output utility.

(3) Establish a "Trust code base" to allow data to be thoroughly verified before it comes in to believe the situation.

(4) Search for the data category before logging on to the data.

Explain each data style, such as the buffer length and integer type.

The strict definition of legitimate user demand, refuse all other requests.

Verify that the test data meets the valid conditions, rather than the improper conditions. This is because there are many improper data conditions and it is difficult to list them carefully.

Ii. Five common ASP. NET security defects

The following provides five examples to illustrate how to enhance the security of application steps in accordance with the above-mentioned initiatives. These examples describe the defects in the Code, the security crisis they bring about, and how to rewrite the least code to effectively defend against the crisis.

2.1 modify parameters

Manipulate ASP. NET domain validators

Blindly believe that user input is the first enemy to secure Web applications. The main source of user input is the parameters submitted in the HTML form. If you cannot strictly verify the legitimacy of these parameters, there is or endanger the security of the server.

The following C # code checks the backend SQL Server database. Assume that the values of the user and password variables are directly taken from the user input:

SqlDataAdapter my_query = new SqlDataAdapter (

"SELECT * FROM accounts WHERE acc_user =" + user + "AND acc_password =" + password, the_connection );

In terms of appearance, these lines of code have no question, but in reality it may attract SQL injection attacks. If the attacker enters "OR 1 = 1" in the user input field, he can log on to the system smoothly. Perhaps, if appropriate misappropriation is added after the interrogation, he can execute the arbitrary Shell call:

; EXEC master .. xp_cmdshell (Oshell command here )--

■ Crisis Analysis

When writing these lines of code, the pioneers sometimes make the assumption that the user's input content only contains "normal" data-in line with the common user name and password, but it does not contain special characters such as quotation marks, which is the foundation of SQL injection attacks. Hackers can use special characters to change the intention of questioning, and then use arbitrary functions or processes.

■ Sanction plan

The domain validators are a mechanism that allows ASP. NET pioneers to limit the value of a domain. For example, to limit the value of a domain entered by a user, you must use a specific expression.

To guard against the above attack, the first method is to prevent special character input such as quotation marks, and the second method is more rigorous, that is, to limit that the content of the input field must belong to the same set of valid characters, for example, "[a-zA-Z0-9] *".

2.2 modify parameter 2 ◎ disadvantages of stopping verification manipulation

However, it is only for each input field to introduce the validators can not guard against all the attack to modify the parameter inspector. When performing a numeric category search, you must specify the correct data category.

That is to say, when manipulating the ASP. NET category search control, you should specify a proper Type Attribute Based on the Data Category required by the input field, because the default value of Type is String.

<! -- The input value must be a number between 1 and 9 -->

<Asp: RangeValidator... MinimumValue = "1" MaximumValue = "9".../>

■ Crisis Analysis

Because the Type attribute value is not specified, the above Code assumes that the Type of the input value is String, so the RangeValidator validator can only ensure that the String starts with a character between 0-9, "0 abcd" will also be recognized.

■ Sanction plan

To ensure that the input value is indeed an Integer, the correct method is to specify the Type attribute as Integer:

<! -- The input value must be a number between 1 and 9 -->

<Asp: RangeValidator... MinimumValue = "1"

MaximumValue = "9" Type = "Integer"

2.3 Information Leakage

◎ Better security of hidden Domains

In ASP. NET applications, information about related applications can be found in the _ VIEWSTATE hiding field of all HTML pages. Because _ VIEWSTATE is base64-encoded, it is often neglected. However, hackers can easily decode the BASE 64 data and get the detailed information provided by _ VIEWSTATE without any effort.

■ Crisis Analysis

By default, __viewstate data will contain:

(1) Dynamic Data from page controls.

(2) The Pioneer explicitly stores the data in ViewState.

(3) the password of the above data.

■ Sanction plan

Configure EnableViewStatMAC = "true" to enable the _ VIEWSTATE data encryption utility. Then, set the machineKey verification category to 3DES, and ASP. NET is required to use the Triple DES symmetric encryption algorithm to encrypt ViewState data.

2.4 SQL Injection Attack

◎ API for manipulating SQL Parameters

As described in the "Modify parameters" section above, the attacker can insert special characters in the input domain to change the intention of SQL interrogation. The fraudulent Database Server performs malicious interrogation.

■ Crisis Analysis

Maliciously obtain information stored in the backend database, such as a list of customer's reputation card numbers.

■ Sanction plan

In addition to the method introduced in the front-use the step Code to ensure that the input content contains only useful characters. The other method that is particularly robust is to manipulate the SQL parameter API (such as ADO.. NET APIs), allowing underlying APIs (rather than step workers) in programming situations to structure the question.

When manipulating these APIs, the pioneer may provide a interrogation template, or a storage process, and then specify a series of parameter values. The underlying API embeds the parameter values into the interrogation template, then, the structure of the review is submitted to the server for review. The benefit of this method is to ensure that the parameters may be correctly embedded. For example, the preparation will implement escape control on the quotation marks to prevent SQL injection attacks. At the same time, the quotation marks in the form are still a useful character for license input, which is also an advantage of manipulating the underlying API.

Follow these steps to modify the "Modify parameters" part of the previous article:

SqlDataAdapter my_query = new SqlDataAdapter ("SELECT * FROM accounts

WHERE acc_user = @ user AND acc_password = @ pass ", the_connection );

SqlParameter userParam = my_query.Select_Command.Parameters.Add (

"@ User", SqlDb. VarChar, 20 );

UserParam. Value = user;

SqlParameter passwordParam = my_query.Select_Command.Parameters.Add (

"@", SqlDb. VarChar, 20 );

PasswordParam. Value = password;

2.5 Cross-Site Scripting

Code the data sent externally

Cross-site scripting (XSS) refers to embedding malicious user input into the response (HTML) page. For example, the following ASP. NET page is simple, but contains a major security defect:

<% @ Page Language = "vb" %>

<Asp

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.