OWASP recommends as defense against command injection to escape all special characters (if a whitelist approach cannot be used).
I wrote a quick PHP script doing this:
$input = $_GET['x'];
$dangerous = array("{", "}", "", "(", ")", "<", ">", "&", "*", "|", "=", "?", ";", "[", "]", "$", "–", "~", "!", ".", "%", "/", ":", "+", "'");
$input = str_replace("\\","\\\\",$input);
foreach ($dangerous as $char) {
$input = str_replace($char,"\\$char",$input);
}
echo passthru("echo '$input'");
echo "<br><br>executed: " . $input ;
However, if I use '
as input, it will result in an error (Unterminated quoted string
).
I wasn't able to bypass the escaping of these characters, but it doesn't seem ideal that an attacker can generate a bash error because of invalid syntax.
Is there a way to bypass the escaping of these special characters?
I know that using a whitelist or existing mechanisms like escapeshellcmd would be recommended. I am more interested in the general idea of bypassing the escaping of special characters.
\'
still terminates the string and you get an error.