php is illustrated using the exec shell command injection method

  • 2020-11-18 06:08:43
  • OfStack

Using system commands is a dangerous operation, especially if you are trying to construct the command to execute using remote data. If contaminated data is used, a command injection vulnerability is created.
exec() is the function used to execute the shell command. It returns the last line of execution and command output, but you can specify an array as the second argument, so that each line of output is stored as an element in the array. The usage is as follows:

<?php
$last = exec('ls', $output, $return);
print_r($output);
echo "Return [$return]";
?>

Assume that the ls command produces the following output when run manually in shell:

$ ls
total 0
-rw-rw-r--  1 chris chris 0 May 21 12:34 php-security
-rw-rw-r--  1 chris chris 0 May 21 12:34 chris-shiflett

When run in exec() using the method in the above example, the output is as follows:

Array
(
  [0] => total 0
  [1] => -rw-rw-r--  1 chris chris 0 May 21 12:34 php-security
  [2] => -rw-rw-r--  1 chris chris 0 May 21 12:34 chris-shiflett
)
Return [0]

This is a convenient and useful way to run the shell command, but it comes at a significant risk. If a command string is constructed using contaminated data, the attacker can execute any command.
I recommend that you avoid using the shell command whenever possible, and if you do, make sure that you filter the data that builds the command string and that you escape the output:

<?php
$clean = array();
$shell = array();
/* Filter Input ($command, $argument) */
$shell['command'] = escapeshellcmd($clean['command']);
$shell['argument'] = escapeshellarg($clean['argument']);
$last = exec("{$shell['command']} {$shell['argument']}", $output, $return);
?>

Although there are several ways to execute the shell command, you must stick to the point that only filtered and escaped data is allowed when constructing the string being run. Other functions of the same class to note are passthru(), popen(), shell_exec(), and system(). Again, I recommend avoiding the use of all shell commands if possible.

Related articles: