Escape Linux Command to Prevent Security Holes From PHP shell_exec Function


In PHP, the function shell_exec takes a string parameter that allows PHP to run the linux commands in the shell e.g. BASH shell. So you have to be careful with that because this is extremely powerful and dangerous. If you allow the command to be changed via users input (e.g. URL get parameter) than harmful commands can be injected.

I have used shell_exec to make simple web-based applications/utility like CURL and FIGLET. Luckily I realized the security holes (so dangerous) before any bad things happen.

1
2
3
$value = $_GET['value'];
$cmd = 'figlet $value';
shell_exec($cmd);
$value = $_GET['value'];
$cmd = 'figlet $value';
shell_exec($cmd);

The above 3 lines of code is straightforward. But if the $value passed by URL-GET is

hello | ls -l

Then the command to execute will be:

figlet hello | ls -l

The pipe line works and the arbitrary command can be executed. Can you image if the user passes | rm -rf / and that will become very nasty situations.

Obviously we don’t want that happens so we can obviously remove these characters that are part of the command.

1
2
3
4
$value = str_replace('|', '', $value);
$value = str_replace(';', '', $value);
...
...
$value = str_replace('|', '', $value);
$value = str_replace(';', '', $value);
...
...

You would need to escape a lot of special characters such as , ; ` | $() because they all can be used to invoke shell commands. Removing them isn’t perfect because it means the users can’t use them as part of the values.

Another easy solution would be to remove the single quote and add a single quote to the whole string value:

1
$value = '\'' . str_replace('\'', '', $value) . '\'';
$value = '\'' . str_replace('\'', '', $value) . '\'';

That is simple, so if value = ‘a | ls -l’ the command will become:

figlet 'a | ls -l' 

And linux will escape all the special characters inside the single quotes, which becomes a single command in this case.

You can also use the following inbuilt PHP function:

1
string escapeshellarg ( string $arg )
string escapeshellarg ( string $arg )

This function escapeshellarg is to escape string characters to be used for shell arguments.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
440 words
Last Post: How to Check CPU (Cores) on VPS/Dedicate Server?
Next Post: Easy Rate Limit in PHP using Simple Strategy - An API Example

The Permanent URL is: Escape Linux Command to Prevent Security Holes From PHP shell_exec Function

Leave a Reply