In-depth analysis of SQL Injection principles

Source: Internet
Author: User
Tags html form input

For Web applications, injection attacks have been around for a long time. Common attacks include SQL injection, command injection, and recent XPath injection. This article takes SQL injection as an example to explain in depth the attack principles at the source code level.

I. Principles of injection attacks

The root cause of injection attacks is that there is no clear distinction between program commands and user data (that is, user input. This gives attackers the opportunity to submit program commands to the We program as user-input data and give orders as desired.

To launch an injection attack, attackers need to mix the "data" that will be interpreted as a command in the conventional input. To succeed, three things must be done:

1. Determine the technology used by Web Applications

Injection attacks are closely related to programming languages or hardware, but these attacks can be moved out by appropriate clicks or simply by trying them one by one. To determine the technology used, attackers can inspect the footer of a Web page, view the error page, check the page source code, or use tools such as Nessus for spying.

2. determine all possible input methods

There are many user input methods for Web applications, some of which are obvious, such as HTML forms. In addition, attackers can interact with Web applications through hidden HTML form input, HTTP header, cookies, and even invisible backend AJAX requests. In general, all http get and POST requests should be user input. To find out all possible user input for a Web application, we can turn to Web proxies such as Burp.

3. Search for user input that can be used for Injection

After finding out all user input methods, we need to filter these input methods to find out which input methods can inject commands. This task seems a little difficult, but here is a tip, that is, pay more attention to the error pages of Web applications, and you can often get unexpected gains from this.

Ii. SQL Injection principles

We have made a general explanation of injection attacks. The following uses SQL injection as an example to give readers a perceptual understanding of injection attacks. As for other attacks, the principles are consistent.

SQL Injection allows attackers to bypass the authentication mechanism and completely control databases on remote servers. SQL is short for the structured query language. It is the de facto standard for database access. Currently, most Web applications use SQL databases to store application data. Almost all Web applications use a SQL database in the background. Like most languages, SQL syntax allows database commands to be mixed with user data. If developers are not careful, user data may be interpreted as commands. In this way, remote users can not only input data to Web applications, you can also execute arbitrary commands on the database.

3. Bypass User Authentication

Here we will explain a simple Web application that requires user identity authentication. Assume that this application provides a logon page, requiring the user to enter the user name and password. The user sends their username and password through an HTTP request. Then, the Web application checks whether the username and password passed by the user match the username and password in the database. In this case, a database table is required in the SQL database. You can use the following SQL statement to create a table:

CREATETABLEuser_table (

IdINTEGERPRIMARYKEY,

UsernameVARCHAR (32 ),

PasswordVARCHAR (41)

);

The preceding SQL code creates a table consisting of three columns. The first column stores the user ID. If someone has been authenticated, use this to identify the user. The second column stores the user name, which consists of up to 32 characters. The third column stores the password, which consists of the hash value of the user's password, because it is too dangerous to store the user's password in plain text, therefore, the hash values of passwords are usually stored. The SQL function PASSWORD () is used to obtain the hash value of the PASSWORD. in MySQL, the output of the function PASSWORD () is composed of 41 characters.

To authenticate a user, the user name and password are compared with the rows in the table. If the user name and password in a row exactly match the user input, then the user passes the authentication and obtains the ID in the row. If the user name and password provided by the user are lonelynerd15 and mypassword, the process of checking the user ID is as follows:

SELECTidFROMuser_tableWHEREusername = 'lonelynerd15' ANDpassword = PASSWORD ('mypassword ')

If the user is located in the database table, the SQL command returns the corresponding ID of the user, which means that the user has passed authentication; otherwise, the return of this SQL command is blank, this means that the user has not been authenticated.

The following is the Java code used for automatic logon. It receives the username and password from the user and authenticates the user through an SQL query:

Stringusername = req. getParameter ("username ");

Stringpassword = req. getParameter ("password ");

Stringquery = "SELECTidFROMuser_tableWHERE" +

"Username = '" + username + "' AND" +

"Password = PASSWORD ('" + password + "')";

Resultsetrs1_stmt.exe cuteQuery (query );

Intid =-1; //-1impliesthattheuserisunauthenticated.

While (rs. next ()){

Id = rs. getInt ("id ");

}

The first two lines of code obtain user input from the HTTP request, and then construct an SQL query starting from the next line. Execute the query and obtain the result in the while () loop. If a user name matches the password pair, the correct ID is returned. Otherwise, the value of id is-1, which means that the user has not passed the authentication. On the surface, if the user name matches the password pair, the user will pass the authentication; otherwise, the user will not pass the authentication -- but is it true? None! The reader may have noticed that SQL commands are not defended here. Therefore, attackers can inject SQL statements into the username or password fields to change SQL queries. For this reason, we carefully study the preceding SQL query string:

Stringquery = "SELECTidFROMuser_tableWHERE" +

"Username = '" + username + "' AND" +

"Password = PASSWORD ('" + password + "')";

The above Code assumes that the string username and password are both data. However, attackers can enter any character as they like. If the user name entered by an attacker is

'Or1 = 1-

The password is

X

Then the query string will look like the following:

SELECTidFROMuser_tableWHEREusername = ''OR1 = 1 -- 'andpassword

= PASSWORD ('x ')

This double-stroke sign tells the SQL parser that all the things on the right are comments, so ignore it. In this way, the query string is equivalent:

SELECTidFROMuser_tableWHEREusername = ''OR1 = 1

Today's SELECT statement is quite different from the previous one, because as long as the user name is a zero-length string ''or 1 = 1, one of the two conditions is true, returns the user ID -- we know that 1 = 1 is always true. Therefore, this statement returns all IDs in user_table. In this case, the attacker puts the SQL command 'or1 = 1 -- rather than data in the username field.

4. Construct SQL Injection code

To successfully inject SQL commands, attackers must convert existing SQL commands of developers into a valid SQL statement. Of course, blind injection is difficult, but this is generally the case:

OR1 = 1-

Or

) OR1 = 1 --

In addition, many Web applications provide error reports and debugging information. For example, when you use OR1 = 1 to perform blind injection on Web applications, the following error messages are often displayed:

Errorexecutingquery:
YouhaveanerrorinyourSQLsyntax;
CheckthemanualthatcorrespondstoyourMySQLserverversionfortherightsyntaxtousenear
SELECT (title, body) FROMblog_tableWHEREcat = OR1 = 1atline1
 

This error details the complete SQL statement. In this case, the SQL database looks forward to an integer rather than a string, so it can be injected into the string OR1 = 1 --, if you remove the single quotes, the injection will be successful. For most SQL databases, attackers can place multiple SQL statements in one row, as long as the syntax of each statement is correct. In the following code, we demonstrate how to set username to OR1 = 1 and set password to x to return the final user ID:

Stringquery = "SELECTidFROMuser_tableWHERE" +

"Username =" + username + "AND" +

"Password = PASSWORD (" + password + ")";

 

 

Of course, attackers can inject other queries, such as setting username:

OR1 = 1; DROPTABLEuser_table ;--

The query will become:

SELECTidFROMuser_tableWHEREusername = OR1 = 1; DROPTABLEuser_table; -- ANDpassword = PASSWORD (x );

It is equivalent:

SELECTidFROMuser_tableWHEREusername = OR1 = 1; DROPTABLEuser_table;

 

 

This statement runs a SELECT statement that is syntactically correct and clears user_table using the sqlddrop command.

Injection attacks do not require blind attacks, because many Web applications are developed using open source code tools. To improve the success rate of injection attacks, we can download free or trial versions of the product, then build a test system on your own system. If an error is found in the test system, it is likely that the same problem exists in all Web applications that use the tool.

V. Summary

We will introduce the root cause of injection attacks to readers in this article, that is, there is no strict distinction between data and commands. Then, through some program source code, the SQL attack is analyzed in detail, so that we have a deep understanding of the SQL Injection mechanism. If you are a web application developer, you should be careful not to blindly trust the user's input, but strictly sanitize the user's input data, otherwise, SQL injection will arrive unexpectedly.

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.