Be very wary of using the exec()
, system()
, passthru()
, and popen()
functions and the backtick (`)
operator in your code. The shell is a problem because it recognizes special characters (e.g., semicolons to separate commands). For example, suppose your script contains this line:
system("ls {$directory}");
If the user passes the value ” /tmp;cat /etc/passwd
” as the $directory
parameter, your password file is displayed because system()
executes the following command:
ls /tmp;cat /etc/passwd
In cases where you must pass user-supplied arguments to a shell command, use escapeshellarg()
on the string to escape any sequences that have special meaning to shells:
$cleanedArg = escapeshellarg($directory); system("ls {$cleanedArg}");
Now, if the user passes ” /tmp;cat /etc/passwd
“, the command that’s actually run is:
ls '/tmp;cat /etc/passwd'
The easiest way to avoid the shell is to do the work of whatever program you’re trying to call in PHP code, rather than calling out to the shell. Built-in functions are likely to be more secure than anything involving the shell.
Here is the list of of Article in this Series:
- PHP – Securing your Web Application : Introduction
- PHP – Securing your Web Application : Filter Input
- PHP – Securing your Web Application : Cross-Site Scripting
- PHP – Securing your Web Application : SQL Injection
- PHP – Securing your Web Application : Escape Output
- PHP – Securing your Web Application : Filenames
- PHP – Securing your Web Application : Session Fixation
- PHP – Securing your Web Application : File Uploads
- PHP – Securing your Web Application : File Access
- PHP – Securing your Web Application : PHP Code
- PHP – Securing your Web Application : Shell Commands
- PHP – Securing your Web Application : More information and Summary
Please share the article if you like let your friends learn PHP Security. Please comment any suggestion or queries.
Thanks Kevin Tatroe, Peter MacIntyre and Rasmus Lerdorf. Special Thanks to O’Relly.