Command Injection DVWA Hard Difficulty

1k Views Asked by At

I am using DVWA in order to learn about security vulnerabilities. In the part of command injection as shown below, the back end code is:

enter image description here

<?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 user
    echo "<pre>{$cmd}</pre>";
}

?>

From my understanding if i give as input || ls then the code should replace || with '' so the injection should not work. Although in my surprise the injection worked producing the output of the file as shown below:

After

1

There are 1 best solutions below

0
On BEST ANSWER

Just one little trap with your replacement array... You need to define || before | as you need to perform replacements on double characters before the single ones. It's an interesting little quirk!

So your array

// Set blacklist
$substitutions = array(
    '&'  => '',
    ';'  => '',
    '| ' => '',
    '-'  => '',
    '$'  => '',
    '('  => '',
    ')'  => '',
    '`'  => '',
    '||' => '',
); 

Should be

// Set blacklist
$substitutions = array(
    '&'  => '',
    ';'  => '',
    '||' => '',
    '| ' => '',
    '-'  => '',
    '$'  => '',
    '('  => '',
    ')'  => '',
    '`'  => '',
);