2017-2018-2 20179205 "Network attack and defense technology and practice" 11th Week operation SQL injection attack and practice

Source: Internet
Author: User
Tags mysql injection sql injection sql injection attack

"Network attack and defense technology and practice" 11th Week operation SQL injection attack and Practice 1. Research on the principle of buffer overflow, at least for two kinds of database to study the buffer overflow principle

?? Inside the computer, the input data is usually stored in a temporary space, the temporary storage space is called a buffer, the length of the buffer has been pre-defined by the program or the operating system. Fill the buffer with data, if the length of the data is longer than the buffer itself capacity, then the data will overflow storage space, and these overflow data will be overwritten on the legitimate data, this is the truth of buffer and buffer overflow.

?? Typically, a byte array is allocated in the stack to hold a string, but the length of the string exceeds the allocated space for the array. c there is no bounds checking for array references, and local variables and state information are present in the stack. In this way, a write to an array element that is out of bounds destroys the state information stored in the stack. A serious error occurs when the program attempts to reload the register or perform a RET instruction using this corrupted state.

void echo(){char buf[8] ;gets(buf) ;puts(buf) ;}

Since the stack is growing to the ground address, the array buffers are growing to high addresses. Therefore, a longer string will cause the gets to overwrite some information stored on the stack.
As the string gets longer, the following information is broken:
The number of characters entered is corrupted state
0---7 No
8---11 The value of the saved%EBX
---15 The value of the saved%EBP
---19 return address
20+ the saved state in caller
If the value of the stored%ebp is destroyed, the base register cannot be restored correctly, so the caller cannot correctly reference its local variables or parameters.
If the return address of the store is broken, the RET instruction will redirect the program to a completely unexpected place.

a more lethal use of buffer overflows is to let the program perform functions that it would otherwise not be willing to execute. This is one of the most common ways to attack a system through a computer network. Typically, a string is entered into the program, which contains the byte encoding of some executable code, called the attack code, and some bytes overwrite the return address with a pointer to the attack code. Then, the effect of executing the RET instruction is to jump to the attack code.

In general, using GET or any other function that can cause storage overflow is not a good programming habit. Unfortunately, many common library functions, including strcpy, strcat, and sprintf, have a single attribute--no need to tell them the size of the target buffer, resulting in a sequence of bytes.

Against buffer overflow attacks

1. Stack randomization

?? In order to insert the attack code into the system, the attacker would not only insert the code, but also insert a pointer to the code, which is also part of the attack string. Generating this pointer requires knowing the stack address where the string is placed. In the past, the stack address of the program was very predictable, and the position of the stack was quite fixed between different machines.
The idea of stack randomization makes the position of the stack change every time the program is run. Therefore, even if many machines are running the same code. Their stack addresses are different.
This is accomplished by allocating a random size space between 0--n bytes on the stack at the beginning of the program. The program does not use this space, but it causes the subsequent stack position to change every time the program executes.

In Linux systems, Stack randomization has become a standard behavior. (Each time you run the same program on Linux, the address of the same local variable is different)

2, Stack damage detection

?? In the C language, there is no reliable way to prevent the cross-border write of an array, but we are able to try to detect it when there is an out-of-bounds write without causing any harmful results.
The latest GCC version adds a stack protector mechanism to the generated code to detect buffer bounds, and the idea is to store a special canary value between any local buffer in the stack and the state of the stack. This canary value is randomly generated every time the program is run, so there is no easy way for an attacker to know what it is.
Before resuming the register state and returning from the function, the program checks whether the canary value has been changed by an operation of the function or by a function call. If it is, then the program terminates abnormally.

3. Restrict executable code area

?? Limit the areas of memory where executable code can be stored. In a typical program, only the portion of memory that holds the code generated by the compiler needs to be executable, and the rest can be restricted to read and write only.
The memory protection of the 64-bit processor now introduces the "NX" (non-executing) bit. With this feature, the stack can be marked as readable and writable, but not executable, checking whether the page can be executed by hardware, without loss of efficiency.

2. Research SQL injection Point discovery and injection technology for different data types SQL injection causes and threats:

Just now. When we visit a Dynamic Web page, the WEB server initiates a SQL query request to the data access layer and executes the SQL statement if permission validation passes.

The SQL requests sent directly from this site are generally not dangerous, but the reality is that it is often necessary to dynamically construct SQL statements in conjunction with the user's input data, and if the data entered by the user is constructed into malicious SQL code, the WEB application does not review the parameters used by the dynamically constructed SQL statement. Pose an unexpected risk.

The main threats to SQL injection are the following:

    • Guess the backend database, which is the most leveraged way to steal sensitive information from a website.
    • Bypass authentication, columns such as bypassing the authenticate login site backstage.
    • Injection can take advantage of the database's stored procedures
2.1 Determining the SQL injection point

Typically, a Url that may have a SQL injection vulnerability is similar to this form: Http://xxx.xxx.xxx/abcd.php?id=XX

There are two main ways to judge SQL injection:

    • Determine if the URL with the parameter has SQL injection?
    • If there is SQL injection, what kind of SQL injection does it belong to?

?? In a asp/php/jsp Dynamic Web page where there may be a SQL injection attack, there may be only one parameter in a Dynamic Web page, and sometimes multiple parameters. Sometimes an integer parameter, sometimes a string argument, cannot be generalize. In short, if it is a dynamic Web page with parameters and this page accesses the database, there is a possibility of Sql injection. If the programmer does not have sufficient security awareness and does not perform the necessary character filtering, there is a large likelihood of SQL injection.

2.2 To determine if there is a SQL injection vulnerability

The most classic single-quote method of judging:

Add a single quotation mark after the argument, such as:


If the page returns an error, there is a SQL injection.

The reason for this is that the number of single quotes does not match, regardless of the character type or the integer type.

Note: If there is no error, it does not mean that there is no SQL injection, because it is possible for the page to filter single quotes, you can use a judgment statement to inject

2.3 To determine the type of SQL injection vulnerability

There are typically 2 types of SQL injection vulnerabilities:

    • Digital type
    • Character type
    • Search Type

?? In fact, all types are generated according to the type of table of the database itself, when we create the table will always have a data type restrictions, and different databases have different data types, but no matter how the common query data type is always distinguished by the number and character, so the injection point will produce the type.

2.3.1 Digital Type judgment:

When the input parameter x is an integral type, the SQL statement type in abc.php is generally as follows:

select * from <表名> where id = x

This type can be judged using classic and 1=1 and and 1=2 :

The input page in the URL address is http://xxx/abc.php?id= x and 1=1 still working, proceed to the next step.
Continuing to enter http://xxx/abc.php?id= x and 1=2 a page run error in the URL address, this SQL injection is a digital injection.
The reasons are as follows:

When entered and 1=1 , the SQL statement is executed in the background:

select * from <表名> where id = x and 1=1

No syntax errors and logical judgments are correct, so return to normal.

When entered and 1=2 , the SQL statement is executed in the background:

select * from <表名> where id = x and 1=2

There is no syntax error but the logic is false, so the error is returned.

Let's use the assumption: if this is a character injection, we should have the following when we enter the above statement:

select * from <表名> where id = ‘x and 1=1‘ select * from <表名> where id = ‘x and 1=2‘

The query statement converts and statements all to a string, and does not have the logical judgment of and, so the above results do not appear, so the assumption is not tenable.

2.3.2 Character type judgment:

When the input parameter x is a character type, typically the SQL statement type in abc.php is roughly the following:

select * from <表名> where id = ‘x‘

We can also use this type and ‘1‘=‘1 and ‘1‘=‘2 to judge:

Enter the page in the URL address to http://xxx/abc.php?id= x‘ and ‘1‘=‘1 run normally, proceed to the next step.
The URL address continues to enter the http://xxx/abc.php?id= x‘ and ‘1‘=‘2 page run error, which indicates that this SQL injection is a character-type injection.
The reasons are as follows:

When input and ' 1 ' = ' 1 o'clock, the background executes the SQL statement:

select * from <表名> where id = ‘x‘ and ‘1‘=‘1‘

The syntax is correct, the logic is correctly judged, so the return is correct.

When input and ' 1 ' = ' 2 o'clock, the background executes the SQL statement:

select * from <表名> where id = ‘x‘ and ‘1‘=‘2‘

The syntax is correct, but the logic is wrong, so it returns correctly.

2.3.3-Search Injection points:

? Emsp; This is a special type of injection. This kind of injection is mainly refers to in the data search without filtering the search parameters, generally in the link address has "keyword= keyword", some do not display the link address, but directly through the search box form submission.
The SQL statements submitted by such injection points are roughly the same:

select * from 表名 where 字段 like ‘%关键字%‘

When we submit an injection parameter of "keyword= ' and[query condition] and '% ' = ', the finished SQL statement submitted to the database is:

select * from 表名 where 字段 like ‘%‘ and [查询条件] and ‘%‘=‘%‘

By looking up the data I have a rough idea of SQL injection, and I know the power of SQL injection. Common techniques for SQL injection include:

    • Use of non-mainstream channel technology
    • Avoid input filtering technology
    • Use a special character
    • Force error generation
    • Using conditional statements
    • Take advantage of stored procedures
    • Inference Technology
    • ........
3. Study the buffer overflow prevention method, at least for two programming languages to carry on the differential research detection method and the precaution measure;

Depending on the steps of the buffer overflow attack, common buffer overflow attack detection techniques can be divided into the following 3 types:

    • The detection method based on input string
    • Detection method based on return address in the protection stack
    • A detection method based on monitoring system calls.
3.1 Detection method based on input string

Detects the input string, determines that it is an overflow attack string, and takes a blocking action to prevent the attacker from injecting the attack code. There are typically 3 ways to build an overflow attack string. As shown in the following:

Buffer greater than ShellCode length:

Buffer less than ShellCode length:

Place the ShellCode in the environment variable:

?? The 1th type of overflow attack string is suitable for cases where the buffer is greater than ShellCode length, and the 2nd overflow attack string is generally used in cases where the buffer is less than ShellCode length, and the 3rd method is to put ShellCode in the environment variable, which is the most common method at present.

?? A number of NOP instructions were added before ShellCode in the 1th and 2nd types of overflow attack strings, because the address of the ShellCode cannot be determined in these 2 cases, but as long as the return address points to any of the NOP instructions before ShellCode, ShellCode Can be implemented, greatly increasing the likelihood of ShellCode execution. These NOP instructions are called Sledge. Other single-byte instructions, such as AAA, can also constitute sledge. Therefore, the buffer overflow attack detection system can determine whether this string is an overflow attack string by checking whether the input string contains a large number of NOP and other instructions that make up the sledge. However, this approach does not apply to detecting a 3rd type of attack. But these 3 types of attack
The ShellCode is included in the keystroke string. Therefore, to determine the basic characteristics of ShellCode, such as does not contain "0x00", contains some special system calls, and then use artificial intelligence, pattern matching, rule matching and other methods to check whether the input string contains ShellCode can also detect whether a buffer overflow attack occurred. These detection can be implemented in the perimeter defense system such as intrusion detection, the advantage is that the implementation is relatively simple, does not increase the cost of the protected system, the disadvantage is that the false negative rate is high, can not detect the non-obvious characteristics of the overflow attack string.

3.2 Detection method based on return address in the protection stack

?? The most critical step in a buffer overflow attack is to alter the program's flow by modifying the function return address, so that a buffer overflow attack can be judged by checking whether the return address is modified before the function call returns. The implementation of this detection can be done by inserting some of the constraints and judgment modules in the source code, and then monitoring the variables and stack areas during the running of the compiled program to detect if an attack occurs. Stackguard and Stackshield are this type of tool, which are extension tools for the GCC compiler to monitor the function return address of the call is normal. Stackguard is essentially inserting a "Canary" word between the in-memory return address and the buffer.

?? Before the function call returns, by checking the word "Canary" to determine if the return address has been modified, if the value of this Canary is changed, it indicates that a buffer overflow attack may be in progress, the program responds immediately, sends an intrusion warning message, and then stops working. To prevent an attacker from constructing the Canary "word, Stackguard chooses" Terminator "and" random number "as the value of the" Canary "word. However, because the "Canary" word is located in a fixed position, it may also be bypassed Stackshield to improve this, creating a new stack to back up the returned address of the protected function. It adds a piece of code at the beginning of the protected function to copy the function return address to a special table, and also adds a section of code at the end of the protected function to copy the function return address from the table back to the stack. This ensures that the function returns correctly.

3.3 Detection method based on monitoring system call

?? If the attacker succeeds in injecting the attack code and changes the program's execution process, the instruction's execution pointer points to the Shellcode's entry address. According to the 3 steps of a buffer attack, ShellCode must also be executed to complete the attack. Therefore, it is possible to detect if a buffer overflow attack occurs by detecting whether there is a ShellCode run. An attacker would want ShellCode to start an interactive shell process with the acquired privileges to accomplish as many things as possible, and hopefully ShellCode as short as possible to be more covert, so the vast majority of ShellCode call system functions. Because monitoring all system calls consumes a lot of system resources, only system calls that are commonly used by ShellCode are monitored, and certain characteristics determine whether a monitored system call is an illegal call to identify whether a protected system is compromised by a buffer overflow. For example, if you find that the return address of a system call is a stack, you can think of it as an illegal call, because very few programs run code on the stack.

Precautionary measures for buffer holes

?? The above three methods are for how to detect the buffer holes that have occurred, although many methods, but relatively troublesome, so we better be able to fundamentally prevent it, to prevent the occurrence of buffer holes. First, in the process of writing a program, the programmer has the responsibility and the obligation to develop the idea of security programming, should be familiar with those who may create loopholes or need to use caution functions, clear those in the programming to be careful use of functions (especially in the use of C language), such as: Get (), strcpy () and so on. During the software testing phase, each buffer in the program is specifically checked for boundary and overflow detection. However, due to the inexperience of the program writers and insufficient testing work, it is not possible to completely avoid buffer overflow vulnerabilities, so these vulnerabilities are already in use and the software being developed is still possible, and need to be monitored in real time when using the software.

?? The second is to use the security language to write programs, should use Java and other secure language programming, because Java in the buffer operation, there is a corresponding boundary check, so can effectively prevent buffer overflow vulnerability. However, Java is not absolutely secure, the Java interpreter is written in C, and C is not a safe language, so the Java interpreter may have a buffer overflow vulnerability and be attacked. Finally, by improving the compiler, the main idea is to add bounds checking in the compiler and the ability to protect the stack, so that the program and code snippets that contain the vulnerability cannot be compiled. Many of the patches for the GCC compiler provide these features, such as Stackguard, and so on.

4. Database injection Attack tool bSQL Hacker

?? bSQL Hacker was developed by Portcullis Labs, and bSQL Hacker is a SQL auto-injection tool (which supports SQL blinds) designed to allow SQL overflow injection to any database. The bSQL hacker is for those who are experienced users and those who want to inject automatic SQL into the population. The bSQL hacker automatically attacks Oracle and MySQL databases and automatically extracts data and schemas from the database.


SQLMAP is an automatic SQL injection tool. It is capable of performing a wide range of database management system back-end fingerprints,
Retrieves the DBMS database, usernames, tables, columns, and enumerates the entire DBMS information. SQLMAP provides the ability to dump database tables and MySQL, PostgreSQL, SQL Server servers to download or upload any file and execute arbitrary code.


Sqlsus is an open source MySQL injection and Takeover tool, Sqlsus written in Perl and based on a command-line interface. Sqlsus can get the database structure, inject your own SQL statements, download files from the server, crawl Web sites writable directories, upload and control backdoors, clone databases, etc.

2017-2018-2 20179205 "Network attack and defense technology and practice" 11th Week operation SQL injection attack and practice

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.