Exec () is a function used to execute shell commands. The following describes how to use its shell injection method to explain that using system commands is a dangerous operation, this is especially true when you try to use remote data to construct the command to be executed. If contaminated data is used, the command injection vulnerability is generated.
Exec () is a function used to execute shell commands. It returns the last line of command output after execution, but you can specify an array as the second parameter, so that each line of output will be saved as an element in the array. The usage is as follows:
The code is as follows:
$ Last = exec ('Ls', $ output, $ return );
Print_r ($ output );
Echo "Return [$ return]";
?>
If the ls command is manually run in shell, the following output is generated:
The code is as follows:
$ Ls
Total 0
-Rw-r -- 1 chris 0 May 21 12:34 php-security
-Rw-r -- 1 chris 0 May 21 :34 chris-shiflett
When running in exec () through the above example, the output result is as follows:
The code is as follows:
Array
(
[0] => total 0
[1] =>-rw-r -- 1 chris 0 May 21 12:34 php-security
[2] =>-rw-r -- 1 chris 0 May 21 12:34 chris-shiflett
)
Return [0]
This method is convenient and useful for running shell commands, but it brings significant risks to you. If contaminated data is used to construct command strings, attackers can execute arbitrary commands.
I suggest you avoid using shell commands if possible. if you want to use it, make sure to filter the data that constructs the command string and escape the output:
The code is as follows:
$ 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 multiple methods to execute shell commands, you must stick to one point. when constructing a running string, only filtered and escaped data can be used. Other similar functions that need attention include passthru (), popen (), shell_exec (), and system (). I reiterate that if possible, we recommend that you avoid using all shell commands.