SQL injection: step-by-step guide

SQL injection

SQL injection

SQL injection means that the web application does not judge the legality of the data input by the user or the filtering is not strict.

The attacker can add additional SQL statements at the end of the query statement defined in the web application without the administrator ’s knowledge In the case of illegal operations, to deceive the database server to perform any unauthorized query, so as to further obtain the corresponding data information.

Table of content

  • Definition
  • Features
  • Principle
  • Harm
  • Injection Process
  • Injection method
  • Attack Characteristics
  • Attack techniques
  • Detection technology
  • Injection precautions


SQL is a structured query language for operating database data. SQL is used when the application data of web pages interact with the data in the back-end database.

SQL injection is to modify the original URL, form field, or data packet input parameters of the Web page into SQL statements, pass them to the Web server, and then pass them to the database server to execute database commands.

For example, the developer of the web application transmits the data or cookie entered by the user directly to the database without filtering or verification (that is, there is an injection point), which may cause the spliced ​​SQL to be executed to obtain information and suggestions to the database. Right, a SQL injection attack occurs.


1. Extensiveness

Any database based on the SQL language may be attacked. Many developers do not perform normative verification and detection of values ​​received from input parameters, Web forms, cookies, etc. when writing Web applications, and SQL injection vulnerabilities usually occur.

2. Concealment

SQL injection statements are generally embedded in ordinary HTTP requests, which are difficult to distinguish from normal statements, so many current firewalls are unable to recognize and warn, and there are many SQL injection variants.

Attackers can adjust the parameters of the attack, so use traditional The method defense SQL injection effect is very unsatisfactory.

3. Great harm

The attacker obtains the database name, table name, and field name of the server through SQL injection, thereby obtaining the data in the entire server, which poses a great threat to the data security of website users.

The attacker can also obtain the password of the background administrator through the obtained data, and then maliciously tamper with the web page. This not only poses a serious threat to the security of database information but also has a significant impact on the security of the entire database system.

4. Easy operation

There are many SQL injection tools on the Internet, which are easy to learn and the attack process is simple and can be used freely without professional knowledge.


SQL injection attack is to modify the SQL statement through operation input to achieve the method of executing code to attack the WEB server.

Simply put, it is the process of inserting SQL commands in the query string of the post / get web form, enter the domain name or page request, and finally causing the webserver to execute malicious commands. A simple example of SQL injection attacks can be illustrated by an example.

Assuming that the URL of a website page is displayed as http://www.example.com?test=123, the URL actually passes the variable test with a value of 123 to the server, which indicates that the current page is the result of a dynamic query on the database.

From this, we can insert malicious SQL statements in the URL and execute them. In addition, in the process of website development, developers use dynamic strings to construct SQL statements to create the required applications. 

In this case, SQL statements are dynamically constructed and used during the execution of the program and can be generated according to different conditions. 

Different SQL statements, for example, need to query the fields in the database according to different requirements. This development process actually leaves a lot of opportunities for SQL injection attacks.


Any application system developed using a database may be a medium for SQL injection attacks. Since 1999, SQL injection vulnerabilities have become one of the common security vulnerabilities. To date, SQL injection vulnerabilities are still in the top 10 in the CVE list.

In 2011, the US Department of Homeland Security, Mitre, and the Sana Research Institute identified SQL injection as the first dangerous security hole. To date, SQL injection is still the primary security threat vulnerability that is difficult to repair (database manufacturers have difficulty preventing SQL injection by maintaining the database's own functions or improving database security strategies).

In 2012, a Barclaycard representative claimed that 97% of data breaches were caused by SQL injection. At the end of 2011 and the beginning of 2012, in less than a month, more than one million web pages suffered SQL injection attacks. 2008 witnessed the economic imbalance caused by SQL injection. Even in the fall of 2010, the official website of the United Nations suffered SQL injection attacks.

In 2014, a hacker group called "TeamDigi7al" attacked a web application called "Smart Web Move" of the US Navy. The incident directly caused the personal information of more than 220,000 members of the US Navy database to be leaked. Afterward, the US Navy spent more than $ 500,000 to make up for the data breach.

In the 2014 Global Threat Intelligence report released by the Japan Telegraph and Telecommunications Corporation (NTT), an alarming number was presented-"The average aftercare expenditure for a small-scale SQL injection attack by an enterprise is usually more than $ 196,000."

With the frequent occurrence of Web security incidents, we have to think about the cost of SQL injection attacks.

Obviously, SQL injection is not an out-of-date security issue. On the contrary, it is a very easy-to-use attack method.

SQL injection can easily make sensitive database information illegally browsed or deleted without requiring sophisticated attacks. In fact, because SQL injection attacks are simple and very efficient, advanced hackers have begun to use some software to automatically search for SQL vulnerabilities in web applications, and use SQL injection automation tools to create zombies and build botnets that can be attacked automatically.

Obviously, SQL injection attacks will not disappear in a short period of time, and the impact caused by it is a major threat that can't be delayed and costly. Dealing with a web application security incident will cost almost $ 200,000. Network security engineers must be aware that research and prevention of SQL injection attacks are necessary and the primary security task.

Injection Process

The first step: SQL injection point detection. Detecting the SQL injection point is a critical step. 

Through proper analysis of the application, you can determine where the SQL injection point exists. 

Generally, as long as the dynamic webpage with input submission and the dynamic webpage access the database, there may be SQL injection vulnerability. If the programmer's information security awareness is not strong, a dynamic SQL statement is used to access the database, and the user's input is not validated, there is a high possibility of SQL injection vulnerability. Generally, the error information on the page is used to determine whether there is a SQL injection vulnerability.

Step 2: Collect background database information. The injection methods and functions of different databases are different, so before injecting, we must first determine the type of database. 

There are many ways to determine the type of database. You can enter special characters, such as single quotes, to let the program return error information. We can make judgments based on the error information prompts. 

You can also use specific functions to judge, such as entering "1 and version ()> 0", The program returns to normal, indicating that the version () function is recognized and executed by the database, and the version () function is a MySQL-specific function, so it can be inferred that the background database is MySQL.

Step 3: Guess the username and password. The naming of tables and fields in the database is generally regular. By constructing special SQL statements in the database, guess the table name, field name, field number, user name, and password in sequence.

Step 4: Find the web background management portal. WEB background management is usually not open to ordinary users. To find the login URL of the background management, you can use Web directory scanning tools (such as www scan, AWVS) to quickly search for possible login addresses, and then try one by one, you can find the login of the background management platform URL.

The fifth step: invasion and destruction. Generally, background management has the higher authority and more functions. After successfully logging in to the background management platform using the previously deciphered user name and password, it can be arbitrarily destroyed, such as uploading Trojan horses, tampering with web pages, modifying and stealing information, etc. Further elevating authority, invading the web server, and database server.

Injection method

Because the rationality of the user's input data was not judged when the program was written, the attacker was able to execute the code in the injection point of SQL Injection to execute, and through the prompt returned by the page, obtain the information required for the next attack. According to the input parameters, SQL injection methods can be roughly divided into two categories: numeric injection and character injection.

1. Digital injection

When the input parameters are integer types, such as ID, age, page number, etc., if there is an injection vulnerability, it can be considered as a digital injection. 

This type of digital injection occurs at most in weakly typed languages ​​such as ASP and PHP. Weakly typed languages ​​will automatically derive variable types. 

For example, if the parameter id = 8, PHP will automatically infer that the data type of the variable id is int. and 1 = 1, it will be deduced as string type, which is a characteristic of weakly typed languages. For strongly typed languages ​​such as Java and C #, if you try to convert a string to an int type, an exception will be thrown and execution cannot continue. Therefore, there are few digital injection holes in strongly typed languages.

2. Character injection

When the input parameter is a character string, it is called a character type. The biggest difference between numeric and character injection is that numeric type does not require single quotes to close, while string types generally use single quotes to close.

Attack characteristic

SQL injection attack is one of the most common methods in web application network attacks at present, with high-security risks, which exceeds buffer overflow to certain extent vulnerabilities, and firewalls on the market cannot effectively detect and prevent SQL injection vulnerabilities.

In order to allow normal network applications to access data on the server-side, the firewall must allow a positive connection from the Internet to the Web server. 

Therefore, once a vulnerability exists in the web network application, an attacker can obtain the right to access the database to gain access to the server where the database is located In some cases, the risk of SQL injection attacks is higher than all other vulnerabilities such as buffer overflow vulnerabilities. SQL injection attacks are widespread, easy to implement, and destructive.

The SQL injection attacker enters the SQL syntax with the malicious structure in the H1TIP request and it is legal.

As long as there is no strict processing in the application, there will be a risk of SQL injection vulnerability. At present, PHP, Perl, Cold Fusion Management, and other technologies and Web applications that combine data management systems such as Oracle, SQLServer, Sybase, and DB2 have found SQL injection vulnerabilities.

Soon after the SQL injection technology was announced, many SQL injection tools such as SQLMAP, etc. appeared on the Internet. Attacking websites and Web applications that have SQL injections can easily obtain their server's control.

Attack technique

1. Blind based on Boolean

Because the web page return value is True or False, Boolean blind injection is a way to obtain database information based on the page return value after injection.

2. Time-based blind betting

When there is no result of Boolean injection (the page display is normal), it is difficult for us to judge whether the injected code is executed, or can we say that the injection point does not exist? 

At this time, the Boolean injection cannot play its role. Time-based blind injection came into being. The so-called time-based blind injection means that we determine whether there is a SQL injection point on the page according to the corresponding time difference of the web page.

3. Joint query injection

The premise of using a joint query for injection is that the page to be injected must have a display bit. 

The so-called joint query injection is to use the union to merge the result set of two or more SELECT statements, so two or more selects must have the same column and the data type of each column is also the same. 

Joint query injection can add order by 9 at the end of the link based on random number injection, according to the return result of the page to determine the number of fields in the site.

4. Injection based on error information

This method can be used only when there is no display bit on the page, but echo mysql_error (); function outputs error information. 

The advantage is that the injection speed is fast, the disadvantage is that the statement is more complicated, and you can only use the limit to guess the solution in sequence. In general, error injection is actually a formulaic injection method, mainly used for displaying no bits in the page, but using echo mysql_error (); when the error message is output.

Detection technology

There are two main types of detection methods for SQL injection. 

First: dynamic monitoring, that is, when the system is running, this method is usually used during the system acceptance phase or the online operation phase, and the system is scanned using dynamic monitoring attacks, and then scanned The result determines whether there is a SQL injection vulnerability. 

Second: Static detection, also known as static code scanning, does an in-depth analysis of the code.

1. Dynamic detection

Dynamic monitoring is divided into two categories: manual monitoring and tool monitoring

Compared with the high cost and high missed detection rate of manual monitoring, tool monitoring is more preferred in the actual production process, but tool monitoring also has greater limitations. 

The reason is that the tool uses packets to determine whether SQL injection is effective. However, it is difficult to accurately determine whether SQL injection exists only by packets, so there is a high false alarm rate. 

2. Static detection

The false-positive rate of static detection is relatively low, the main reason is that the core characteristics of SQL injection vulnerabilities are more obvious.

  • Use the database interaction code.
  • Using string concatenation to construct dynamic SQL statements.
  • Use unfiltered untrusted data.
When routinely checking whether there is a SQL injection vulnerability in the application system, due to the obvious characteristics of the static scanning code, the low false-positive rate, and the direct reading of the relevant code, the advantage of reducing the total amount of work, usually use static scanning.

Injection Precautions

SQL injection attacks are very harmful, and it is difficult for firewalls to intercept attacks. The main SQL injection attack prevention methods include the following aspects.

1. Hierarchical management

Perform hierarchical management of users and strictly control the permissions of users. For ordinary users, it is forbidden to grant database creation, deletion, modification, and other related permissions. 

Only system administrators have the authority to add, delete, modify, and check. 

For example, in the above example, the user added a drop table to the query statement. It must not be allowed to execute, otherwise, the database security of the system cannot be guaranteed. Therefore, through the design restrictions of permissions.

This allows even malicious attackers to embed relevant attack codes when submitting data. But because the permissions are set, the code cannot be executed. Thereby reducing the security threat of SQL injection to the database.

2. Parameter passing

When programmers write SQL language, it is forbidden to write variables directly to SQL statements, and related variables must be passed by setting corresponding parameters.

Thereby suppressing SQL injection. Data input cannot be directly embedded in the query statement. At the same time, we must filter the input content and filter out the unsafe input data. Or the input variable can be passed by parameter. This can prevent SQL injection attacks to the greatest extent.

3. Basic filtration and secondary filtration

Before the SQL injection attack, the intruder submits "and" and other special characters by modifying the parameters to determine whether there is a vulnerability, and then writes SQL injection statements through various characters such as select and update.

Therefore, to prevent SQL injection, you must check the user input to ensure the security of data input. When specifically checking the input or submitted variables, characters such as single quotes, double quotes, and colons are converted or filtered to effectively prevent SQL injection. 

Of course, there are many dangerous characters. When obtaining the parameters submitted by the user, you must first perform basic filtering, and then perform secondary filtering according to the function of the program and the possibility of user input to ensure the safety of the system.

4. Use safety parameters

In order to effectively suppress the impact of SQL injection attacks, the SQL database. Special SQL security parameters were set when designing the SQL Server database. When programming, you should try to use security parameters to prevent injection attacks. Thus ensuring the security of the system.

The SQLServer database provides the Parameters collection. Its function in the database is to perform type checking and length verification of the data.

When the programmer adds the Parameters collection during programming, the system will automatically filter out the execution code in the user input and identify it as Character value. 

If the user input contains malicious code, the database can also filter it out during the inspection. At the same time, the Parameters collection can also perform mandatory inspections. Once the check value is out of range. An abnormal error will occur in the system, and the information will be sent to the system administrator to facilitate the administrator to take corresponding preventive measures.

5. Vulnerability scanning

In order to prevent SQL injection attacks more effectively, as system management, in addition to setting up effective preventive measures, it should be found that there are security holes in SQL attacks.

System administrators can purchase SQL vulnerability scanning tools of some specialized systems, and through professional scanning tools, they can scan the corresponding vulnerabilities in the system in time. 

Although the vulnerability scanning tool can only scan for SQL injection vulnerabilities, it cannot prevent SQL injection attacks. However, system administrators can take security precautions according to different situations to block corresponding vulnerabilities through the scanned security vulnerabilities, so as to close the door of SQL injection attacks to ensure the security of the system. 

6. Multi-layer verification

The functions of the current website system are getting larger and more complex. In order to ensure the security of the system, the visitor's data input must go through strict verification before entering the system. 

The input that fails verification is directly denied access to the database, and an error message is sent to the upper system. At the same time, verify the relevant input information of the visitor in the client access program, so as to prevent simple SQL injection more effectively. 

However, if the lower layer of the multi-layer verification passes the verification data, then an attacker who bypasses the client can access the system at will. Therefore, when conducting multi-layer verification, each level must cooperate with each other. Only effective verification protection on the client and system side can better prevent SQL injection attacks.

7. Database information encryption

Traditional encryption and decryption methods can be roughly divided into three types:

a. Symmetric encryption: That is, both the encrypting party and the decrypting party use the same encryption algorithm and key. The preservation of the key of this scheme is very critical because the algorithm is public and the key is confidential. Once the key is leaked, Hackers can still easily decrypt. Common symmetric encryption algorithms are AES, DES, etc.

b. Asymmetric encryption: that is, different keys are used for encryption and decryption. The key is divided into a public key and a private key. The data encrypted with the private key must be decrypted using the public key, and the data encrypted with the public key must also be decrypted. To decrypt with the corresponding private key, common asymmetric encryption algorithms are RSA and so on.

c. Irreversible encryption: The hash algorithm is used to make the data unable to be decrypted back to the original data after encryption. Such hash algorithms are commonly used: md5, SHA-1, etc.

Post a Comment

Previous Post Next Post