Section 6.3. Command Injection


6.3. Command Injection

The use of system commands is a dangerous operation, and this is particularly true when you use remote data to construct the command to be issued. When tainted data is used, this represents a command injection vulnerability.

The exec( ) function is a popular function used to execute a shell command. It returns the last line of the output of the command, but you can specify an array as the second argument, and each line of output is stored as an element of that array. It can be used as follows:

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

Assume that the ls command provides the following output when executed manually from the 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 executed with exec( ) as shown in the prior example, the following output is generated:

     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 useful and convenient way to execute shell commands, but this convenience heightens your risk. If tainted data is used to construct the string to be executed, an attacker can execute arbitrary commands.

I recommend that you avoid using shell commands when possible and, when you must use them, ensure that you use only filtered data to construct the string to be executed, and always escape your 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 you can execute shell commands in many different ways, the best practice is to be consistentensure that you use only filtered and escaped data when constructing the string to be executed. Other functions that require careful attention include passthru( ), popen( ), shell_exec( ), and system( ). If at all possible, I recommend avoiding the use of shell commands altogether.




Essential PHP Security
Essential PHP Security
ISBN: 059600656X
EAN: 2147483647
Year: 2005
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net