Injection Protection Guide

Source: Internet
Author: User
Tags html encode servervariables sql injection attack
Author: Feng Qingyang Source: egeneration v4
In recent times, network attacks have become more prevalent, and many sites have been hacked or even replaced by the home page for no reason. Most websites are attacked because of vulnerabilities in website programs. attackers can gain webshells to gain higher server host permissions. However, the way to obtain webshell is concentrated on the SQL injection attack method. What is SQL injection attacks? From the official explanation: When an application uses the input content to construct dynamic SQL statements to access the database, SQL injection attacks will occur. If the Code uses stored procedures, which are passed as strings containing unfiltered user input, SQL injection attacks will also occur. SQL injection may allow attackers to log on to the database using applications to execute commands. This problem can become very serious if applications connect to the database using a privileged account. In other words, SQL injection attacks use vulnerable data access code and allow attackers to execute arbitrary commands in the database. If the application uses unrestricted accounts in the database, attackers can execute queries and commands more freely, resulting in greater threats. It is worth noting that traditional security measures (such as using SSL and IPSec) cannot prevent SQL injection attacks.

Common vulnerabilities that make data access code vulnerable to SQL injection attacks include

· Weak input verification

· Dynamically construct SQL statements without using type-safe Parameters

· Log on to a database with excessive privileges

To cope with SQL injection attacks, be sure:

· Restrict and purify input data

· Use type-safe SQL parameters for data access. These parameters can be used together with stored procedures or dynamically constructed SQL command strings. Parameter execution type and length check, and make sure that the code injected into the database is considered as text data (rather than executable statements ).

· Use accounts with limited permissions in the database. Ideally, only the execution permission should be granted to the selected stored procedure in the database, and the direct table access permission is not provided.

· Verify the type, length, format, and range of the input content. Do not accept numeric values if you do not want them. Consider where the input comes from. If it comes from a trusted source and you know that you have performed thorough input verification on the source, you can choose to ignore data verification in the data access code. If data comes from untrusted sources or is used for deep defense, data access methods and components should verify the input.
To sum up.

How to effectively prevent SQL injection attacks has become the focus of security protection: This article reposted the source of egeneration time e3i5.com

Because ASP is easy to learn and universal, many sites have chosen to use ASP to build their own web sites. ASP is a script-level programming language, which is VBScript or JavaScript. More sites use VBscript scripts as the foundation for writing. However, unfortunately, VBScript requires much loose exception capture (Debug) and data type declaration than JavaScript, with no mandatory requirements, this brings convenience and potential risks. (Due to the habits of Some programmers, when using VBScript to write ASP programs, we often ignore exception capture (Debug) and Data Type declarations) therefore, in terms of preventing web injection attacks, it seems "more than enough ". Back to our topic: when talking about SQL injection, we first came up with a look for injection points. In many cases, Web injection is based on ASP Request objects.

Quote: Example (1): http: // target/index. asp? Id = 10

The first step to prevent SQL injection attacks is to use various security measures to monitor the ASP request object (request, request. querystring, request. form, request. cookies and requests. servervariables) to ensure the reliability of SQL commands. Like other ASP Request objects (reques, request. querystring, request. form, request. cookies and requests. servervariables) user input attack methods are generally concentrated on the expected input variable of the script is a digital variable (ID) (Example 1 ), of course, we can't just look at digital variables: This article reposted the source of egeneration time e3i5.com

Quote: Example (2): http: // target/index. asp? Username = elegant

For example, the variables referenced in example (2) are passed as string variables.
Variables are transmitted by URL in either of the above two ways. First, it is a numeric variable; second, it is a string variable. The SQL injection vulnerability occurs mainly because of the programmer's negligence and carelessness. If it is not filtered out or not strictly filtered, it will leave it to attackers for attack. The following describes how to prevent them:
· Proactively protect the source of this article from egeneration time e3i5.com
What is proactive protection? Active protection does not filter illegal strings, but actively provides a range of string input to prevent SQL injection attacks. Many websites start with filtering ASP Request objects, and only passively filtering known attack characters. For example, the following program: program block (1)

Quote: function htmlencode (STR)

STR = Replace (STR ,";",";")

Str=server.html encode (STR)

STR = Replace (STR ,"'","'")

STR = Replace (STR ,"--","--")

STR = Replace (STR ,"/","/")

STR = Replace (STR, vbcrlf ,"
")

Htmlencode = Str

End Function

The above program is converted from a forum program, which filters out special characters such as semicolon, <,>, single quotation marks, --,/, &, and soft carriage return conversion. Imagine if the above filtering is not strict, it would be a failure. For example, if the program block (1) does not filter the string in the form of "../", it may cause unnecessary troubles and risks in filling in some single tables. If we adopt an active defense method that restricts the input Character Set, use a more efficient regular expression, such as [0-9a-za-z]: program block (2)

Quote: Regular Expression of Chinese characters:/[^/x00-/xFF]/g

Email Regular Expression:/^ [/W.-] + @ ([0-9a-z] [/W-] +/.) + [A-Z] {2, 3} $/I

String consisting of digits, 26 English letters, or underscores: ^/W + $

URL: ^ [A-Za-Z] +: // (/W + (-/W + )*)(/. (/W + (-/W + )*))*(/? /S *)? $

Positive Integer: ^ [0-9] * [1-9] [0-9] * $

Full numeric format:/[^/d]/g

Application:

Function checkexp (patrn, strng)

Dim RegEx, match

Set RegEx = new Regexp

RegEx. pattern = patrn

RegEx. ignorecase = true

RegEx. Global = true

Matches = RegEx. Test (strng)

Checkexp = matches

End Function

Example:

True is returned if STR is a string consisting of digits, 26 English letters, or underscores. Otherwise, false is returned.

The efficiency of filtering dangerous characters is greatly improved by actively limiting the input type of characters, and the relative security is also greatly improved. Only invalid characters are filtered. Hu ~ Who knows which characters are illegal under which circumstances? Therefore, you must take the initiative and actively perform filtering. In addition, we advocate limiting the input Character Set, rather than preventing the use of character restrictions. under specific conditions, filtering characters is much better than limiting the input range. Everyone must learn how to use it flexibly.

· Database query method this article reposted the source egeneration time e3i5.com
It is found that when many sites perform database queries, Rs. EOF or Rs. Bof is used as the query result. The EOF and BOF attributes of the RS (cursor) indicate that the cursor is at the end of the data or at the beginning of the data, indicating that no corresponding data is found. Most sites use the following method to query existing database data during user login and user registration: block (3)

Quote:

For example, if the username and password variables are not filtered out due to programmer negligence or other reasons, the SQL injection vulnerability may occur. It is not safe to use Rs. BOF or Rs. EOF as the basis for database data traversal. From the security point of view, we should use the following method as the basis for judgment: program block (4) This article reposted the source of egeneration time e3i5.com

Quote:

With the existence of the if rs ("username") = username then statement (in red), an additional check is required during the verification. This not only satisfies the correctness of the SQL query statement, the correct judgment is provided only when the queried data is consistent with the input data.

· Detection of other database queries
Many site problems may occur in this phase. In fact, the most problems in this phase are also the easiest to solve. Because many programmers do not have good programming habits, they only implement functions, do not pay attention to the security of their programs, or do not notice more details. This is also an aspect that causes the site program to be attacked. The specific problems are mainly focused on the following aspects:
1. Returned Field Values for the query
Many friends like to use the following statements for query, such as program block (5)

Quote: SQL = "select * from [user] Where uid =" & ID & "order by uid DESC"

In short, if there is a limit on the number variable (ID), the entire statement may be safe. However, using select * to query all fields may cause more security problems. I recommend that you use select * as few as possible in your own programs to query fields in the data table.
2. Variable detection in digital format this article reposts source egeneration time e3i5.com
This should be the most widely used variable type in ASP. Many people think that it is difficult to filter string-type variables, so many of them use numerical IDS as variable transmission. The excessive use often makes it easy for programmers to forget whether a digital ID has been used for variable type detection. As mentioned above, VBScript does not strictly declare Data Types in other languages. To define a new variable in Java, first define the data type of the variable, for example:

Quote: 1. String A = "good day ";

2. int A = 3;

3. Public static string madethisexample (string PWD, int sold)

{

String key = string. concant (PWD, sold );

String result = loopaddr ("madethisout", key );

Return result;

}

With a strict data type, we can filter data based on different data types or capture exceptions. However, ASP Security has no advantages in this regard. For example, the following ASP program snippet: This article reposted the source egeneration time e3i5.com

Quote: dim str_a, int_ B

Str_a = request ("str_a ")

Int_ B = request ("int_ B ")

In the above program segment, we can see the expected string str_a and integer int_ B. However, in ASP, we can define data without data types, this makes the program writer have to pay attention to forcing the Data Types of some variables and capturing exceptions. For example, the integer variable int_ B is used as the integer judgment:

Quote: dim int_ B

Int_ B = CINT (Request ("int_ B "))

In this way, int_ B is forced to be an integer variable. When int_ B is not an integer, the program will produce an error: "The character type does not match"
When judging numeric variables, we generally use the following functions:

Quote: CINT, clng, isnull, isempty, isnumeric, etc.

In our common programs, the above judgment functions are enough to force the Integer Operation on all the request object data type variables. You can even write a common verification function for global verification. I will not mention the validation function here. many friends on the Internet have written some filter functions. You can search for them as a reference.

3. character string format validation this article is reprinted. Source: egeneration time e3i5.com
Using a string as a variable does not have a function like an integer variable. Is it tricky to use such a variable. In the case of no flexibility, you can only use your scalp to filter rigid illegal characters. I feel that there are too many items to be filtered, what's even more depressing is that the characters to be filtered are still used by users. What should I do in this case? They all blame themselves for not paying attention when writing the program. when the problem is found, there are many characters in the user's data that will be blocked. In fact, the way variables in string format are verified is similar to the method described above.
(1) only the specified characters can be entered in combination with the given character set. For details, refer to the program block (2)
(2) Use cursor data verification, similar to the user login method. Example: block (6)

Quote: dim SQL, RS

Dim type

Type = request ("Stype ")

SQL = "select ArticleID, articletypes, articletitle, articlewrter, adddate from [Article] Where articletypes = '" & type &' "order by ArticleID DESC"

Set rs = conn. Execute (SQL)

If not (Rs. EOF or Rs. bof) then

If RS ("articletype") = type then

Document list operations

Else

Variable Error operation

End if

End if

As shown in block (6), no matter what the content of the string variable is, as long as it cannot pass if RS ("articletype ") = type then detection is regarded as illegal content of this string variable. Such an operation would be much better than simply filtering out invalid characters. The ghost knows what new injection methods will appear on a certain day. Even if some special characters are blocked, other injection methods can be used.

4. Variable Length background detection this article reposts source egeneration time e3i5.com
Why do we need to add length detection after programs that have already been detected? (Well, some friends are not at ease. Joke de) this also depends on the needs of the program. The foreground script-level restriction is only limited to the filtering of a client. As an attacker, attackers can completely break through the client restrictions by some means, to prevent such attacks, we can only start with the server program and add a test to the maximum length of a single table, the first is to prevent writing data to the database from failing because the string length is too large. The second is to effectively prevent SQL injection attacks. Variable length limit: block (7)

Quote: The LEN () function is used to determine the length of a string. If the length is exceeded or the value is re-paid or an error message is returned, the program is terminated. For example:

5. Prevent remote Injection
This situation is really easy to forget. This is also the case in Mobile Network forums. For example, the data processing File Uploaded By a file does not validate the remote information and untrusted source information, and a small bug in the verification program is added, the entire website is hacked due to a bit of security configuration issues on the server. I believe many of my friends are suffering from this situation. Not only are Forum programs, but also data processing programs on other sites that do not have permission verification or filter requests from untrusted regions, this makes it possible for me to change the website page without knowing the password. One thing to be reminded is that many friends are afraid that their websites will be hacked. If they make slight changes to the background login address of the free program they use, they will think everything is fine, in particular, the login page and the data processing page are not on the same page, and the data processing page does not filter requests in untrusted areas. Even if you change the login port, attackers can still forge data for login. In particular, some non-URL injection attacks, such as SQL Injection on a single table, are only used for script-level filtering on a single table on the page, when attackers do not filter requests from untrusted regions on the Data Processing page, they generally submit illegal statements on the local forged page, which is hard to prevent. The code to prevent remote injection is provided below again: program block (8) This article reprints the source e. e3i5.com

Quote:

· Description of data security
It is worth mentioning that if you have the financial ability to use SQL database + server, note that the permission to open a database account should be as close as possible to the ideal situation. You should only grant the execution permission to the selected stored procedure in the database, table access permissions are not provided, and some special commands and files on the server are deleted or renamed.
Users who use the ACCESS database should pay attention to protecting the security of the conn. asp file. It is best to use exception capture to block the error information of the database connection. To prevent leakage of sensitive information. Example: block (9)

Quote:

In addition, users who use the ACCESS database should pay attention to the anti-download protection of the database. The steps are as follows:
1. Use the ASP program to write Ole data to the database. The written content is <%
2. Rename the database to the file ending with ASA. Because the IIS server has higher protection for the ASA file than the ASP file, we select the ASA file as the end extension of the Access database file.
3. Add a # number to the changed database name to prevent SQL Injection problems in other programs and prevent the "cross-database query" operation.

In the end, do not forget to delete the installation file of the Site program. Otherwise, the installation file "black" should be dropped, because this will lead to a long memory.

· Postscript
Seeing that the network is not calm recently, I feel that this Article can help or remind webmasters. Take a quick look at the program on your website. Maybe the above problems may exist on an inconspicuous page. Hu ~ Even more worried is that some portal sites in China also have similar problems, and even some security companies, websites of national institutions. It seems that the form is imminent, and the administrators should be ready to work. The source of this article is egeneration time e3i5.com.
If you have any questions, please go to www.e3i5.com. Thank you!

References:
1. http://www.securiteam.com/securityreviews/5DP0N1P76E.html
2. http://msdn.microsoft.com/msdnmag/issues/04/09/SQLInjection/default.aspx
3. http://www.4guysfromrolla.com/webtech/061902-1.shtml
 

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.