PHP command injection function and DVWA command injection practice

Source: Internet
Author: User
Tags explode

Command Injection Vulnerability

Note: Analysis of command injection vulnerability and function parsing with command injection vulnerability

Functions with Command Injection Vulnerability: System (), exec (), PassThru (), shell_exec (), ' ' (Same as shell_exec () function)

I. Command injection vulnerability based on the DVWA Environment (SHELL_EXEC)

1. Function usage
String shell_exec (String command)
Command to execute
2, Low Level
Source:

<?phpif( isset( $_POST[ ‘Submit‘ ]  ) ) {    // Get input    $target = $_REQUEST[ ‘ip‘ ];    // Determine OS and execute the ping command.    if( stristr( php_uname( ‘s‘ ), ‘Windows NT‘ ) ) {        // Windows        $cmd = shell_exec( ‘ping  ‘ . $target );    }    else {        // *nix        $cmd = shell_exec( ‘ping  -c 4 ‘ . $target );    }    // Feedback for the end user    echo "<pre>{$cmd}</pre>";}?>

SOURCE Analysis:
function first determine the environment of the system, if it is win to execute the first command, if the Linux execution of the command with the-C option, the Linux ping command is always executed. Only add-c specifies the number of hops sent to stop.
You can see that the user's input is not handled in any place where the user input is received. It is not difficult to see that this is a typical command injection vulnerability. And children are the easiest.
Let's test it normally:

As you can see, the normal return is the data returned by Ping.
Let's test the vulnerability by executing this command:
Construct our statement: 10.39.1.4 | NET user
Explanation: | This means that the output of the preceding command is the input to the subsequent command.
NET user to see which users exist on the current system
Test:

You can see that there are three users in the current system. If you use it as XXX, you can use the command to create a user. It's not a demo.
Vulnerability Analysis: Directly executes commands in a function without processing any input from the user.

Knowledge Expansion:
;-Semicolons when the Linux command executes, you can execute several commands directly, separated by semicolons between commands and commands.
& Execute the command after the previous command executes
&& the preceding command executes successfully before you can execute the following command
| The previous command output results in the following command input
|| The previous command execution failed before the subsequent command is executed

3, Medium level
Source:

<?phpif( isset( $_POST[ ‘Submit‘ ]  ) ) {    // Get input    $target = $_REQUEST[ ‘ip‘ ];    // Set blacklist    $substitutions = array(        ‘&&‘ => ‘‘,        ‘;‘  => ‘‘,    );    // Remove any of the charactars in the array (blacklist).    $target = str_replace( array_keys( $substitutions ), $substitutions, $target );    // Determine OS and execute the ping command.    if( stristr( php_uname( ‘s‘ ), ‘Windows NT‘ ) ) {        // Windows        $cmd = shell_exec( ‘ping  ‘ . $target );    }    else {        // *nix        $cmd = shell_exec( ‘ping  -c 4 ‘ . $target );    }    // Feedback for the end user    echo "<pre>{$cmd}</pre>";}?>

SOURCE Analysis:
The Str_replace () function replaces some characters in a string with other characters (case-sensitive).
$target = Str_replace (Array_keys ($substitutions), $substitutions, $target), replace the user input with && or, empty.
The other part of the basic and low difference is not small.
Here the source of the user's input to the initial filtering, filtering out some can execute the command at the same time, but we know that have the same role of symbols more than && and; Therefore, command injection is still possible.
Command Injection test:
Construct statement: 10.39.1.4 & NET User
& the previous command executes and then executes the following command
Test:

Still getting the results of the implementation

Vulnerability Analysis: The source of this level although the user's input set filter, but not the special symbol filtering completely, just set the blacklist is not enough, you do not know what the user will input, resulting in a person can also exploit this vulnerability.

4、 high级别
Source:
<?php

if (Isset ($_post[' Submit ')) {
Get input
$target = Trim ($_request[' IP ');

// Set blacklist$substitutions = array(    ‘&‘  => ‘‘,    ‘;‘  => ‘‘,    ‘| ‘ => ‘‘,    ‘-‘  => ‘‘,    ‘$‘  => ‘‘,    ‘(‘  => ‘‘,    ‘)‘  => ‘‘,    ‘`‘  => ‘‘,    ‘||‘ => ‘‘,);// Remove any of the charactars in the array (blacklist).$target = str_replace( array_keys( $substitutions ), $substitutions, $target );// Determine OS and execute the ping command.if( stristr( php_uname( ‘s‘ ), ‘Windows NT‘ ) ) {    // Windows    $cmd = shell_exec( ‘ping  ‘ . $target );}else {    // *nix    $cmd = shell_exec( ‘ping  -c 4 ‘ . $target );}// Feedback for the end userecho "<pre>{$cmd}</pre>";

}

?>

SOURCE Analysis:
This level of source code and medium level of the source code is not big difference, just add more symbols to blacklist.
Through this really can be effective defense before the many ideas.
Test:
Input 10.39.1.4 | NET user

I can't use those methods anymore. I have not found a suitable method for the specific use.

Vulnerability analysis: Just do blacklist, is always not safe enough, as long as the blacklist is not complete, it is not very safe. Even if you think the list is complete. There may be a presence that you do not know can be exploited.

5, impossible level
Source code:

<?phpif (Isset ($_post[' Submit ')) {//Check ANTI-CSRF token checktoken ($_request[' User_token '), $_sessi    on[' Session_token '], ' index.php ');    Get input $target = $_request[' IP '];    $target = Stripslashes ($target);    Split the IP into 4 octects $octet = Explode (".", $target); Check IF Each octet are an integer IF ((is_numeric ($octet [0])) && (Is_numeric ($octet [1]) && (Is_numeric ($octet [2]) && (Is_numeric ($octet [3])) && (sizeof ($octet) = = 4)) {//If a        LL 4 octets is int ' s put the IP back together. $target = $octet [0]. ‘.‘ . $octet [1]. ‘.‘ . $octet [2]. ‘.‘ .        $octet [3];        Determine OS and execute the ping command. if (Stristr (Php_uname (' s '), ' Windows NT ')) {//Windows $cmd = shell_exec (' ping ' $target)        ;        } else {//*nix $cmd = Shell_exec (' ping-c 4 '. $target); }//FeedBack for the end user echo "<pre>{$cmd}</pre>"; } else {//Ops.    Let the user name theres a mistake Echo ' <pre>error:you has entered an invalid ip.</pre> '; }}//Generate anti-csrf Tokengeneratesessiontoken ();

SOURCE Analysis:
The Explode () function converts the string into an array. Here is the IP that we entered into an array
It then determines whether the first four groups of the array are numbers, and there are four objects in the array. Not satisfied will be an error alert. This means that you are only allowed to enter four sets of numbers.
If the judgment is true, then the four sets of numbers will be connected together and then the ping command can be done.
Do not test, such a source has been put an end to all your commands to inject xxx.

Second, the eval () function caused by the command injection vulnerability

1. Function usage
Eval (Phpcode)
PHPCODE Specifies the PHP code to be computed. The execution of each code is usually terminated with a semicolon.
2. Environment Source Code :

<?php$var = "var";if(isset($_GET["name"])){    $arg = $_GET["name"];    eval("\$var=$arg;");    echo "\$var = ".$var;}?>

Construct the statement:

Name=phpinfo ()

Test results:

3. Examples of CTF topics
Local inclusions in the title address Bugku: http://120.24.86.145:8003/
Topic Analysis:
Source:

<?php     include "flag.php";     $a = @$_REQUEST[‘hello‘];     eval( "var_dump($a);");     show_source(__FILE__); ?>

Construct the statement:
Hello = File (' flag.php ')
Parsing, when a parameter receives a constructed statement, the code becomes
Eval (var_dump (File (' flag.php ')))
The Eval function executes the PHP code without the function body, and the file () function reads the entire document into an array. Var_dump () function output.
So the result of execution is to output the contents of the flag.php in the form of an array.

Get flag

Iii. vulnerabilities caused by the system () function

1. Function Usage:
System (String Command,int &return_var)
Command to execute
Return_var state value after the execution of the stored command
2. Environment Source code:

<?php$cmd = $_GET[‘cmd‘];if(isset($cmd)){    echo system("dir".$cmd);}?>

Construct the statement:
cmd=| NET user

Test:

Through the vulnerability we have access to the system in which users, the same we can also be used in this way in the system to create our own users. And can be added to the Administrators group. This is not the point.

Iv. vulnerabilities caused by the shell_exec () function

1. Function Usage:
Shell_exec (String command)
Command to execute
2. Environment Source code:

<?php$cmd = $_GET[‘cmd‘];if(isset($cmd)){    echo "

4. Test:
Construct statement: | NET user


The implementation method is the same as the previous function. The same function also has the EXEC () and the symbol

V. Vulnerabilities caused by the PassThru () function
1. Function Usage:
void PassThru (String command, int &return_var)
Command to execute
Return_var the status value after the execution of the command

Similar to the EXEC () function, the PassThru () function is also used to execute external commands (command). This function is used instead of the exec () or system () function when the executed Unix command outputs binary data and needs to be delivered directly to the browser.
2. Environment Source code:

<?php$cmd = $_GET[‘cmd‘];if(isset($cmd)){ echo passthru($cmd);}?>

3. Testing
Construct Statement cmd=net user

Get a list of users

Vi. Summary
        总结以上所有函数漏洞造成的命令注入漏洞,每一个例子都是因为没有对用户的输入进行处理。在防御漏洞的时候,一定明白一个道理,所有用户的输入都是有害的。所有的输入都是不值得相信的。

PHP command injection function and DVWA command injection practice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.